我有一个编程类(class),目前有一个作业,要根据用户在 C 程序中输入的月份和日期显示假期名称。
每当我编译并运行该程序时,都没有错误。但是,如果我输入任何月份并按 Enter 键,它只会返回元旦,并且不会询问日期。它应该需要月份和日期,然后显示相应的假期,但它似乎不起作用。
我想知道您是否可以提供有关正确语法的输入。
下面是我尝试创建的代码:
#include <stdio.h>
int main () {
char m;
int d;
printf("Enter Month: ");
scanf("%c", &m);
printf("Enter Date: ");
scanf("%d",&d);
if (m ="January" && d == 1)
printf("New year's day ");
else if (m ="July" && d ==1 )
printf("Canada day ");
else if (m = "December" && d ==25)
printf("Christmas day ");
else
printf("%c %d does not correspond to a fixed-date holiday ", m, d);
return 0;
}
最佳答案
程序中必须更改的内容
1 - 不要使用char
类型来存储string
,您可以使用字符数组。
2 - =
不是比较运算符,它是赋值运算符,因此您应该使用函数 strcmp()
它用于比较两个字符串并返回不同字符的数量(如果两个字符串相同则返回 0)。
#include <stdio.h>
#include<string.h>
int main()
{
char m[10];
int d;
printf("Enter Month: ");
scanf("%s", m);
printf("Enter Date: ");
scanf("%d", &d);
if ( !(strcmp(m, "January")) && d == 1)
printf("New year's day ");
else if (!(strcmp(m, "July")) && d == 1)
printf("Canada day ");
else if (!(strcmp(m, "December")) && d == 25)
printf("Christmas day ");
else
printf("%s %d does not correspond to a fixed-date holiday ", m, d);
return 0;
}
关于c - 根据c程序中输入的月份和日期显示假期名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50713045/