I'm writing a code that calculates the difference in days between 2 given dates. Note that each month is considered to be equal to 30 days and each year equal to 360 days.
I'm getting the following warning/errors and I don't seem to understand why:
这是我的代码:
#include <stdio.h>
int dif_days(struct Date Date1, struct Date Date2);
struct Date
{
int Day;
int Month;
int Year;
};
int main()
{
struct Date Date1;
struct Date Date2;
printf("\n Please enter the first date: ");
scanf("%d %d %d ", &Date1.Day, &Date1.Month, &Date1.Year);
printf("\n Please enter the second date: ");
scanf("%d %d %d ", &Date2.Day, &Date2.Month, &Date2.Year);
int diff = dif_days(Date1, Date2);
printf("\n The difference in days is: %d \n", diff);
return 0;
}
int dif_days(struct Date Date1, struct Date Date2)
{
// variable declaration
int difference;
int Day, Month, Year; // The final days/months/years
// for the days
if (Date1.Day > Date2.Day)
Day = Date1.Day - Date2.Day;
else
Day = Date2.Day - Date1.Day;
// for the months
if (Date1.Month > Date2.Month)
Month = Date1.Month - Date2.Month;
else
Month = Date2.Month - Date1.Month;
// for the years
if (Date1.Year > Date2.Year)
Year = Date1.Year - Date2.Year;
else
Year = Date2.Year - Date1.Year;
difference = Day + Month*30 + Year*360;
return difference;
}
最佳答案
在 dif_days()
的函数原型(prototype)中使用它之前,您需要声明 struct Date
。
您可以移动 struct
的整个定义,使其位于函数原型(prototype)之前,或者您可以通过在函数原型(prototype):
struct Date;
此外,您还需要从 scanf()
格式字符串中删除尾随的空白字符。 This plays havoc with interactive input, and does not do what people usually seem to expect.请注意,%d
指令会自动忽略前导空白字符,事实上,唯一不会忽略前导空白的 scanf()
指令是 %c
、%n
和 %[]
。
当我们讨论 scanf()
主题时,您应该检查调用 scanf()
返回的值以确保输入符合预期.一旦格式字符串中的匹配失败,scanf()
将继续前进,而不会在其余变量中存储任何内容。当代码尝试使用不确定的值时,无效输入将导致未定义的行为。如果输入了三个数字,此处 scanf()
将返回 3,对于基本验证,您可以在继续之前检查用户是否确实输入了三个数字。
关于c - error : conflicting types, 错误:形参2的类型不完整,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53799277/