为什么当我进入三月或七月时,我的代码没有给我正确的输入

Why does my code not give me the correct input when I enter March or July?

本文关键字:代码 我的 输入 七月 三月 为什么      更新时间:2023-10-16

我是新来的,需要帮助处理我的代码。我必须计算三月和七月的平均气温。阵列在一个单独的文件夹中。这是我的密码。感谢

float sumofArray = 0;
int j = 0;
char Month;
float AverageMeanMarch = 0;
float AverageMeanJuly = 0;
printf("Please type the month for average mean temperature. (March/July) n");
scanf_s("%c", &Month);
if (Month == "March" && Month == "march") 
{
    for (j = 0; j < 31; j++)
        sumofArray = sumofArray + MeanMarch[j];
    AverageMeanMarch = sumofArray / 31;

    printf("The average mean temperature for the month of March is %.2f. n", AverageMeanMarch);
} 
else if (Month == "July" && Month == "july")
{
    for (j = 0; j < 31; j++)
        sumofArray = sumofArray + MeanJuly[j];
    AverageMeanJuly = sumofArray / 31;
    printf("The average mean temperature for the month of March is %.2f. n", AverageMeanJuly);
}
else
{
    printf("Invalid Month n");
}

您使用了错误的条件运算符,而不是&amp;,您想使用||-因为在区分大小写的生态系统中,字符串不能既是"字符串"又是"字符串"。

此外,您不能使用c中的"=="运算符进行字符串比较,因为您只进行指针比较,您需要的是"strcmp(str1,str2)",如果字符串匹配,则其输出为0。

所以,你的代码应该是:

if (strcmp(Month,"March") == 0 || strcmp(Month,"march") == 0) 

并在七月做同样的改变。

而且,正如有人在评论中提到的那样,您将"Month"声明为单个字符,您可以将其初始化为足够容纳一个月的char[],也可以初始化为char*,并使用malloc相应地分配内存。

此外,您使用了带有%c作为参数的scanf,这意味着从用户输入中只检索一个字符。

有关更多信息,请参阅:strcmp

您没有将月份作为数组。。您将月份作为一个字符变量,它将存储单个值。。。

相关文章: