代码的思想是从标准输入中读取单个字符。如果读取的是"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)如何处理此代码并使其正常工作?
发布于 2020-12-02 16:33:47
“未声明”错误的原因:在预处理阶段之后,if语句将变为:
对if(y == letter)的
if(YES == letter)更改对else if(n == letter)的
else if(NO == letter)更改这两条语句是经过预处理后进入编译阶段的输入。显然,没有声明y和n变量。因此,出现了错误。
解决方案:
#define YES 'y'
#define NO 'n'在这些更改之后,if语句将是(在预处理阶段之后):
对if('y' == letter)的
if(YES == letter)更改对else if('n' == letter)的
else if(NO == letter)更改在这里,'y'和'n'是字符常量,而不是变量。所以,你不会得到“未声明”的错误。
发布于 2020-12-02 18:37:48
首先,您应该删除包含# 。
其次,在定义中,将y和x声明为变量,而不是字符,以声明为字符,应如下所示:'x‘,'y’
#include <stdio.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("\nFUZZY");
getchar();
return 0;
}发布于 2020-12-02 21:21:12
您应该使用y和n作为字符'y‘和'n’
https://stackoverflow.com/questions/65104415
复制相似问题