c - Days between dates will not compile -
i have been trying work. need input 2 dates (mm dd) , have program tell me amount of days between 2 dates. reason when try use month 2 (february) dont think registering indicated having 28 days. when enter same date cant "0". please thank you
#include <stdio.h> #include <stdlib.h> //constructs dates calculation struct date{ int month; int day; };//end date int main() { struct date first, second; //creates 2 dates calculate int finaldays = 0; int total = 0; int = 0; int valid=0; printf("enter first date \n"); scanf("%d %d", &first.month, &first.day); //user input: first date if (first.month == 1||3||5||7||8||10){ if(first.day > 31){ printf("invalid day\n"); valid += 1; } } else if (first.month == 4||6||9||11 ){ if (first.day > 30){ printf("invalid day\n"); valid += 1; } } else if (first.month == 2){ if(first.day > 28){ printf("invalid day"); valid += 1; } } printf("enter second date\n"); scanf("%d %d", &second.month, &second.day); // user input: second date if (second.month == 1||3||5||7||8||10){ if(second.day > 31){ printf("invalid day\n"); valid += 1; } } else if (second.month == 4||6||9||11 ){ if (second.day > 30){ printf("invalid day\n"); valid += 1; } } else if (second.month ==2){ if(second.day > 28){ printf("invalid day"); valid += 1; } } if (first.month == second.month && first.day == second.day){ printf("days between dates: 0"); valid += 1; } //prints statement if month invalid if(first.month > 12 || second.month > 12 || first.month<1 || second.month<1){ printf("invalid date: invalid month"); } //prints statement if second date precedes first if(second.month<first.month){ printf("invalid. second date cannot precede first date."); } if (second.month==first.month && second.day<first.day){ printf("invalid. second date cannot precede first date."); } if(first.month==second.month){ finaldays = (second.day - first.day); printf("days between dates: %d", finaldays); valid+=1; } if(first.month == 1||3||5||7||8||10||12) // days remaining in first month total = 31 - first.day; else if(first.month == 4||6||9||11) total = 30 - first.day; else if(first.month == 2) total = 28 - first.day; for(i = first.month + 1; < second.month; i++) { if(i == 3||5||7||8||10||12) total += 31; else if(i == 4||6||9||11) total += 30; } total += second.day; if(valid == 0){ printf("first date: %d %d \n", first.month, first.day); printf("second date: %d %d \n", second.month, second.day); printf("days between dates: %d", total); } return 0; } //end main
if (first.month == 1||3||5||7||8||10){
this won't want do. evaluated (first.month == 1)||3||5||7||8||10, evaluate true non-zero months.
this better written case statement;
switch (first.month) { case 1: case 3: case 5: case 7: case 8: case 10: /* handle 31 day months */ ... break; case 4: case 6: case 9: case 11: /* handle 30 day months */ ... break; case 2: /* handle february */ ... break; default: /* handle invalid month */ break; }
Comments
Post a Comment