0

我是一个学习 C 的新手,我尝试使用 if else 制作一个简单的计算器。但是当我执行代码时,即使“if”中的语句为假,它仍然在那里执行 printf 命令?

这是代码

#include <stdio.h>
int main(int argc, char const *argv[])
{
  int opt;
  int x, y;
  float res;

  printf("\nSelect an operation (+1, -2, /3, *4): ");
  scanf("%d", &opt);


  printf("Pick the first number: ");
  scanf("%d", &x);
  printf("Pick the second number: ");
  scanf("%d", &y);


  if(opt = 1) {
      res = x + y;
      printf("\nThe result is: %f", res);
  }
    
  else(opt = 2); {
      res = x - y;
      printf("\nThe result is: %f", res);
  }

    return 0;
}
4

1 回答 1

0

存在三个问题。

第一个是您正在使用赋值运算符 = 而不是比较运算符 == 例如

if(opt = 1) {
     ^^^^
    res = x + y;
    printf("\nThe result is: %f", res);
}

第二个问题是您在 if 语句的 else 部分使用表达式语句而不是条件

else(opt = 2); {
            ^^^

所以这个复合语句在 else 语句之后

else(opt = 2); 

{
    res = x - y;
    printf("\nThe result is: %f", res);
}

总是被执行。

在 else 之后使用表达式是语法错误

else (opt = 2); 

如果您要使用嵌套的 if 语句

至少你需要写

else if (opt == 2) 
{
    res = x - y;
    printf("\nThe result is: %f", res);
}

请注意,根据 C 标准,main 的第二个参数是在没有限定符const的情况下声明的,即 main 的声明应该如下所示

int main(int argc, char * argv[])
于 2022-03-01T14:07:27.153 回答