以下是我为EEL4834课的家庭作业编写的代码的一部分。这只是为了练习,而不是为了分数。
我的问题是,当我的if语句为真时,编译器将其视为假。我相信它是正确的,因为我通过在else语句中打印变量的值来测试语句,并且为我的变量打印的值就是我在if语句中要求的值。
代码…
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char a, b, c, d, box;
float box1;
printf("nPlease enter the box type as a, b, c, or d: ");
scanf("n%c", &box);
if (box == a){
box1 = .05;
printf("%f", box1);
}
else{
printf("n%cn", box);
}
system("pause");
return 0;
}
输出如下所示:
Please enter a box type as a, b, c, or d: a
a
Press any key to continue . . .
输出告诉我盒子实际上是a,但是如果盒子是a,那么为什么编译器不把if语句当作真呢?为了简单起见,我省略了包含b、c或d选项的if语句。
如果这是愚蠢的事情,我道歉。我试着使用搜索引擎,任何相关的东西似乎都比我的问题复杂得多。谢谢你的帮助。if (box == a){
比较变量box
和变量a
(未定义)。
你应该将它与字符
进行比较if (box == 'a') {
这也意味着您可以摆脱变量a
, b
, c
和d
,因为它们不用于任何东西:
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char box;
float box1;
printf("nPlease enter the box type as a, b, c, or d: ");
scanf("n%c", &box);
if (box == 'a') {
box1 = .05;
printf ("%f", box1);
} else {
printf("n%cn", box);
}
system("pause");
return 0;
}
您是在比较名为a
的变量,而不是文字字符'a'
。
要理解我的意思,可以参考下面的教程