当我尝试进行6/3的除法时,输出结果如下2 / -1431650288。代码有什么问题? 我在c中的程序是这样的:
#include <stdio.h>
int main(){
char Operator;
int num1, num2;
printf("Enter the operator in which you want to perform calculation(+, -, *, /)\n");
scanf(" %c", &Operator);
if (Operator == '/'){
printf("Enter two numbers: ");
scanf(" %d %d", &num1, &num2);
if (num2==0){
printf("\a Denominator must be greater than 0.\n");
}
else{
printf(" %d / %d", num1/num2);
}
}
else{
printf("Enter two integer numbers: ");
scanf(" %d %d", &num1, &num2);
if(Operator =='+'){
printf(" %d + %d = %d", num1, num2, num1+num2);
}
else if(Operator == '-'){
printf(" %d - %d = %d", num1, num2, num1-num2);
}
else if(Operator == '*'){
printf(" %d * %d = %d", num1, num2, num1*num2);
}
else{
printf("\t \a Invalid Operator.\n");
}
}
}
答案 0 :(得分:2)
此行:
printf(" %d / %d", num1/num2);
第一个'%d'是num1 / num2的结果,这就足够了。第二个%d和'/'字符不应在此处。更改为:
printf(" %d ", num1/num2);
此外,出于您的目的,开关盒结构更适合代码可读性(我认为也是更好的优化)