2017-02-26 117 views
-1

这是我正在处理的问题的一部分。闰年部分未正确返回。无论我是否投入闰年,它都会在二月份返回29。我究竟做错了什么?为什么我的功能在C中无法正常工作?

#include <stdio.h> 
#include <stdbool.h> 

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

int main (void) 
{ 
    struct date now; 
    void numberOfDays (struct date v); 
    bool findLeap (struct date v); 
    printf("Enter the date in this format mm/dd/yyyy: "); 
    scanf("%i", &now.month, &now.day, &now.year); 

    numberOfDays(now); 

    return 0; 
} 

void numberOfDays (struct date v) 
{ 
    int daysOfMonth; 
    bool findLeap (struct date v); 

    if (v.month == 4 || v.month == 6 || v.month == 9 || v.month == 11) 
     daysOfMonth = 30; 

    else if (v.month == 2) 
    { 
     findLeap(v); 
     if (findLeap) 
      daysOfMonth = 29; 
     else 
      daysOfMonth = 28; 
    } 

    else 
     daysOfMonth = 31; 

    printf("Number of days in month: %i", daysOfMonth); 
} 


bool findLeap (struct date v) 
{ 
    bool isLeap; 

    if (v.year % 4 == 0 && v.year % 100 != 0 || v.year % 400 == 0) 
    { 
     isLeap = true; 
    } 
    else 
    { 
     isLeap = false; 
    } 

    return isLeap; 
} 
+0

你'scanf'是错误的 - 三个值,但格式字符串中只有一个。 'scanf(“%i”,...' - >'scanf(“%i%i%i”,...' –

+0

是的,我之前已经把它改正了,但是在尝试所有我没有改变的东西它回来了。谢谢。 – crawfbigg

回答

1
findLeap(v); 
if (findLeap) 

以上不上的findLeap返回值分支,它总是如此。就是这样,因为函数标识符会隐式转换为函数指针,并且在条件中检查时只会计算为true。

所以只写它正确:

if (findLeap(v)) 

哦,我可能会建议一个更好的名字?由于函数的目的是回答查询,我认为它的名字应该像一个一样。我会去isLeapYear

+0

哇。谢谢。我会试试看。真的很感谢帮助! – crawfbigg

相关问题