【发布时间】:2023-03-19 05:42:02
【问题描述】:
代码思想是从标准输入中读取单个字符。如果读取“y”或“n”,程序应分别打印“YES!”或“NO!”。
我尝试在 if 块中使用 #define 指令:
#include <stdio.h>
#include <stdbool.h>
#define YES y
#define NO n
int main()
{
char letter = ' ';
printf("for Yes enter : y\nfor No enter : n\n");
letter = getchar();
if (YES == letter)
{
printf("YES!");
}
else if (NO == letter)
{
printf("NO!");
}
else
{
printf("this option is not available");
}
printf("FUZZY");
getchar();
return 0;
}
这会导致以下错误:
Ex1.c: In function 'main':
Ex1.c:5:13: error: 'y' undeclared (first use in this function)
#define YES y
^
Ex1.c:13:5: note: in expansion of macro 'YES'
if(YES == letter)
^~~
Ex1.c:5:13: note: each undeclared identifier is reported only once for each function it appears in
#define YES y
^
Ex1.c:13:5: note: in expansion of macro 'YES'
if(YES == letter)
^~~
Ex1.c:6:12: error: 'n' undeclared (first use in this function)
#define NO n
^
Ex1.c:17:10: note: in expansion of macro 'NO'
else if(NO == letter)
如何使这段代码工作?
【问题讨论】:
-
用完全你定义的宏替换宏,然后问问自己这是否有意义。 IE。
if (y == letter)???你不是说if ('y' == letter)吗? -
你正在输入一个字符并且你已经定义了一个变量的别名
标签: c if-statement variables char