使用switch语句制作一个简单的计算器

时间:2016-08-15 05:33:18

标签: c switch-statement calculator

我创建了一个使用'switch'语句编写简单计算器的程序。如果我先取整数输出&然后是操作员输出,b的值总是显示为“0”。 (代码在这里给出)但是,如果我首先采用运算符输出,程序工作正常。这可能是什么原因?感谢。

int a;
int b;
char sign;

printf("Enter two required integers: ");
scanf("%d", &a);
scanf("%d", &b);

printf("Enter the operator(+ or - or * or /): ");
scanf(" %s", &sign);


switch(sign){

    case '+': printf("The summation of %d and %d is %d", a,b, a+b);
              break;

    case '-': printf("The subtraction of %d and %d is %d", a,b, a-b);
              break;

    case '*': printf("The product of %d and %d is %d", a,b, a*b);
              break;

    case '/': printf("The division of %d and %d is %d", a,b, a/b);
              break;

    default: printf("Enter the right operator noob!");
}

return 0;

}

2 个答案:

答案 0 :(得分:5)

scanf(" %s", &sign);

这不正确。 signchar因此它只能存储1个字符,但您正在尝试读取一个字符串,该字符串需要超过1个字符才能覆盖内存。

而是使用

scanf(" %c", &sign);

答案 1 :(得分:0)

这是一个基本问题。您应该记住, char 可以包含键盘中的单个字符。另一方面,当您进行字符变量输入或输出时,您应该使用%c来实现此目的。另一方面,我们知道,字符串是使用多个字符组合构建的。字符串变量用char

声明
  

变量[大小];

对于字符串输入或输出,您需要使用%s。由于您在此处未使用“字符串”,您需要将%s替换为%c ,这应该可以解决您的问题!