【发布时间】:2013-08-29 02:46:37
【问题描述】:
#include <stdio.h>
int main ()
{
char odd, even, answer;
int x = -16;
printf("Choose, even or odd?");
scanf("%c", &answer);
if (answer == odd)
{
while (x < 15)
{
x++;
if (!(x % 2 == 1) && !(x % 2 == -1))
continue;
printf("%d\n", x);
}
printf("Look! Odd numbers!\n");
return 0;
}
else if (answer == even)
{
while (x < 15)
{
x++;
if ((x % 2 == 1) && (x % 2 == -1))
continue;
printf("%d\n", x);
}
printf("Look! Even numbers!\n");
return 0;
}
else
{
printf("That's not a valid response");
return 0;
}
}
抱歉,我是新手,遇到了问题。
输出总是以“else”选项结束。
我对 if 和 else if 的布尔值做错了什么?
【问题讨论】:
-
odd未初始化。根据您的编译器,它要么是用户几乎永远不会输入的\0,要么是一些垃圾,它是否会与用户输入的内容相匹配。 -
是的,奇偶有垃圾值。
-
避免使用
scanf输入char值,改用getchar()。如果您使用scanf,它可能需要一个额外的语句,如fflush(stdin)或一个虚拟getchar()来刷新输入流。
标签: c if-statement boolean