2015-11-01 92 views
0

我寫了一個C程序,計算兩個日期之間的天數。不幸的是,它不能正確編譯。我不知道爲什麼。有人可以幫我修復代碼嗎?看起來SCANF和PRINTF函數存在一些問題。我甚至沒有機會輸入我自己的日期。C程序,計算兩個日期之間的天數

這是我得到的輸出: 非法日期 -1607965827

請幫助我。提前致謝!

#include <stdio.h> 
#include <stdlib.h> 

int days_in_month[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; 

struct date { 
    int day; 
    int month; 
    int year; 
}; 

int leap_year(int year) { 
    if(year%400==0) return 1; 

    if(year%4==0 && year%100!=0) return 1; 

    return 0; 
} 

int correct(struct date d) { 
    if(d.day < 1 || d.day > days_in_month[d.month]) return 0; 

    if(d.month < 1 || d.month > 12) return 0; 

    return 1; 
} 

int number_of_days(struct date d) { 
    int result = 0; 
    int i; 

    for(i=1; i < d.year; i++) { 
     if(leap_year(i)) 
      result += 366; 
     else 
      result += 365; 
    } 

    for(i=1; i < d.month; i++) { 
     result += days_in_month[i]; 

     if(leap_year(d.year) && i == 2) result++; 
    } 

    result += d.day; 
    return result; 
} 

int main() { 
    struct date first, second; 
    int days; 

    scanf("%d %d %d", first.day, first.month, first.year); 
    scanf("%d %d %d", second.day, second.month, second.year); 

    if(!correct(first) || !correct(second)) { 
     printf("Illegal date\n"); 
    } 

    days = number_of_days(first) - number_of_days(second); 

    printf("%d", days); 

    return 0; 
} 
+3

您對'scanf'的使用是錯誤的。通過指針來告訴讀取數據的位置。 – MikeCAT

+0

當你運行它時,你的程序是否行爲異常?如果你能夠運行它,它會正確編譯。 – Steve

+0

我在代碼中看不到任何C++。 –

回答

1

您需要使用的傳遞給scanf函數參數的地址(使用&)

0

這裏有兩個問題: -
1.在main(),first.day是變量的名稱,而是我們必須通過scanf中變量的引用(地址)(「%d」,& first.day);

2.您的日子可能是負面的,如果(第二次日期大於第一次),您確定可以解決該問題。

0

scanf()的錯誤使用方法。 %d預計匹配int *,而不是int。另外,請始終檢查輸入函數的返回值。你會節省時間。除非返回代碼如預期的那樣,否則不要相信像first.day這樣的輸入有希望獲得有效值。 @MikeCAT

一個很好的編譯警告錯誤匹配的格式。啓用所有編譯器警告或獲取新的編譯器。

// scanf("%d %d %d", first.day, first.month, first.year); 
if (scanf("%d %d %d", &first.day, &first.month, &first.year) != 3) { 
    puts("Bad input"); 
    return -1; 
} 

的其他問題包括:

days_in_month[d.month])不考慮閏年。 @BLUEPIXY
int main()不可攜帶/正確 - 使用int main(void)`。

小問題:
leap_year(),與1582年前的問題。可以在correct()年增加年測試。 if (year > 1582) good();
int範圍可能不足以用於日號,請使用long
for(i=1; i < d.year; i++)效率低下。
避免幻數如i == 2
更常見的是通過地址傳遞結構比值。
"%d%d%d"也可以代替"%d %d %d"

BYW:很好的使用結構。

相關問題