[英]Is there something wrong with my code to give me the wrong output?
所以我必须编写一个程序,让我知道用户输入的月份中的日期。 它可以编译并运行,但它给我的唯一 output 是 30 天。 我正在使用驱动程序.c 文件、days.c 文件和 days.h 文件。
我已经尝试更改我的变量并重新排列我的 if else 语句的顺序,但没有任何改变
这是我的驱动程序中的代码。c 文件
#include <stdio.h>
#include "days.h"
int main()
{
int month;
int year;
//user enters month
printf("Enter a month (1-12): ");
scanf("%d", &month);
while(month != 0)
{
if(days_in_month(month, year) == 31)
{
printf("This month has 31 days\n");
}
else
{
printf("This month has 30 days\n");
}
if(days_in_month(month, year) == 28)
{
printf("This month has 28 days");
}
printf("Enter a month (1-12): ");
scanf("%d", &month);
}
return 0;
}
这是 days.c 文件中的代码
int days_in_month(int month, int year)
{
//variables
int month_given;
int num_days;
if (month_given== 1 || month_given== 3 || month_given== 5 || month_given== 7 || month_given== 8 || month_given== 10 || month_given== 12)
{
num_days== 31;
}
else if(month_given== 4 || month_given== 6 || month_given== 9 || month_given== 11)
{
num_days== 30;
}
else(month_given== 2);
{
num_days== 28;
}
}
它应该给出 30 天、31 天或 28 天,具体取决于用户输入的月份
output之所以给你30天是因为...
The function "days_in_month" is supposed to return an integer but you are not returning one explicitly.The function, thus, defaults to returning an integer implicitly but it is not what is expected, this causes the if(days_in_month(month, year) == 31)
条件每次都失败,代码在else
块中打印文本。
除此之外,代码中还有其他不准确之处:
num_days
是否相等(例如: num_days== 31
)。 这应该是num_days = 31
。else(month_given== 2);
是不正确的。“else”是默认情况,应该跟一个语句。 它不检查条件。while
语句还应该检查大于 12 的输入。就像这样while(month != 0 && month < 13)
实施更正将产生一个工作代码(如下所列)......但有 scope 需要改进。
1.变量“year”已声明但未在任何地方使用。您应该收集此变量的输入并实现一个条件以显示二月的正确日期,具体取决于年份是否为
闰年与否。最好在“主要”中。
2.您可以只调用一次“days_in_month”并根据条件检查返回值。
int main()
{
int month;
int year;
//user enters month
printf("Enter a month (1-12): ");
scanf("%d", &month);
while(month != 0 && month < 13) //input between 1 and 12
{
if(days_in_month(month, year) == 31)
{
printf("This month has 31 days\n");
}
else if(days_in_month(month, year) == 28)
{
printf("This month has 28 days\n");
}
else //tagging else at the end
{
printf("This month has 30 days\n");
}
printf("Enter a month (1-12): ");
scanf("%d", &month);
}
return 0;
}
天.c
int days_in_month(int month, int year)
{
//variables
int month_given;
int num_days;
month_given = month; //assigning month to month_given
if (month_given== 1 || month_given== 3 || month_given== 5 || month_given== 7 || month_given== 8 || month_given== 10 || month_given== 12)
{
num_days= 31;
}
else if(month_given== 4 || month_given== 6 || month_given== 9 || month_given== 11)
{
num_days= 30;
}
else //removed the conditional check (month_given== 2);
{
num_days= 28;
}
return num_days; //returning num_days
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.