为什么当我进入三月或七月时,我的代码没有给我正确的输入
Why does my code not give me the correct input when I enter March or July?
我是新来的,需要帮助处理我的代码。我必须计算三月和七月的平均气温。阵列在一个单独的文件夹中。这是我的密码。感谢
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");
}
您使用了错误的条件运算符,而不是&;,您想使用||-因为在区分大小写的生态系统中,字符串不能既是"字符串"又是"字符串"。
此外,您不能使用c中的"=="运算符进行字符串比较,因为您只进行指针比较,您需要的是"strcmp(str1,str2)",如果字符串匹配,则其输出为0。
所以,你的代码应该是:
if (strcmp(Month,"March") == 0 || strcmp(Month,"march") == 0)
并在七月做同样的改变。
而且,正如有人在评论中提到的那样,您将"Month"声明为单个字符,您可以将其初始化为足够容纳一个月的char[],也可以初始化为char*,并使用malloc相应地分配内存。
此外,您使用了带有%c作为参数的scanf,这意味着从用户输入中只检索一个字符。
有关更多信息,请参阅:strcmp
您没有将月份作为数组。。您将月份作为一个字符变量,它将存储单个值。。。
相关文章:
- C++我的数学有什么问题,为什么我的代码不能正确循环
- 我的字符计数代码计算错误.为什么
- 为什么我的C#代码在调用回C++COM直到Task时会暂停.等待/线程.加入
- 为什么我的代码在输出中增加了93天
- 我的简单if-else语句是如何无法访问的代码
- 0-1背包代码中的错误.我的代码中有什么错误
- 我的代码中有错误吗?使用BGI图形的C++代码对我不起作用
- 不确定要在我的main中放入什么才能使我的代码正常工作
- 尝试链接我的着色器时,我收到错误代码"error c5145 must write to gl_position"
- 在我的代码中,获得最大的Pair Wise产品C++和输出并不总是正确的
- 代码在我的计算机上运行良好,但是在将其提交给coursera时遇到未知的信号11问题
- 为什么我需要C++中不同的排序格式来对这个USACO代码上的数组和优先级队列进行排序
- 为什么我的C++代码中出现'Segmentation Fault: 11'行?
- 是否值得降低我的代码的可读性,以便在出现内存不足错误时提供异常安全性?
- 为什么我的C++程序的程序集输出充满了 .ascii,没有汇编代码?
- 无法在我的堆排序代码中找到错误.无法正确执行.C++
- 如何重写全局方法名称以在调用原始方法之前将我的代码推到前面
- 为什么我的 BaseClass:Method 代码编译(带有单冒号)?
- 我的代码运行良好,但在游戏循环中中断
- 8谜题代码.我的队列没有填充,我找不到错误的位置