c - 嵌套 if 语句 : expected declaration or statement at end of input

标签 c if-statement

我们老师布置的作业是编写一个程序,要求输入两个整数 xy 以及一个字符 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/

相关文章:

c++ - 嵌入式 Linux 中链接 'libstdc++' 库已损坏

C++检查数据是否相等

vba扫描列如果为0则删除,如果不等于下一行则插入行

PHP:在if语句中分配多个变量

c - 在运行时为文件分配唯一编号

c - 将结构字段传递给 C 中的函数

c - 如何在 C 中为多个 UDP 数据包设置超时?

python - 使用 libclang 查找匿名枚举

java - 以最有效和可读的方式进行条件初始化

Java 令人困惑的三元 Sonar 违规问题