我们老师布置的作业是编写一个程序,要求输入两个整数 x
和 y
以及一个字符 z
。为 z
输入的字母可以是 a
,它会将两个整数相加,s
会将它们相减,m
乘法和 d
除法。
老师试图在类里面解释多个“if”“else”语句;但是,恐怕我无法确定丢失的“{”所在的位置。如果能更好地理解这一点的人可以解释缺少“{”的原因和位置,将不胜感激。
#include <stdio.h>
int main(void)
{
char let;
int x;
int y;
int a;
int s;
int m;
int d;
printf("Enter command letter \n");
scanf("%c", &let);
printf("Enter both integers \n");
scanf("%d%d%c", &x, &y);
if (let==a)
{
a=x+y;
printf("x+y is %d \n", a);
}
else
{
if (let==s)
{
s=x-y;
printf("x-y is %d \n", s);
}
else
{
if (let==m)
{
m=x*y;
printf("x*y is %d \n", m);
}
else
{
d=x/y;
printf("x/y is %d \n", d);
}
}
return(0);
}
最佳答案
这是典型的缩进问题。
您肯定知道的一件事是,同一个 IF 不能有两个“else”。如果您遵循您的代码,您将看到:
if (let==s)
{
s=x-y;
printf("x-y is %d \n", s);
}
else
{
if (let==m)
{
m=x*y;
printf("x*y is %d \n", m);
}
else
{
d=x/y;
printf("x/y is %d \n", d);
}
这是错误的。
现在是更正后的版本
if (let==s)
{
s=x-y;
printf("x-y is %d \n", s);
}
else
{
if (let==m)
{
m=x*y;
printf("x*y is %d \n", m);
}
else //REINDENTED THIS ELSE, AND THE ERROR BECOMES VISIBLE
{
d=x/y;
printf("x/y is %d \n", d);
}
}//THIS IS THE ONE MISSING
关于c - 嵌套 if 语句 : expected declaration or statement at end of input,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10956916/