我的计算器有问题。我想对计算器进行编程,但是它也可以与字母一起“工作”。如果输入字母“ s”和“ u”,则得到答案0。该如何修复?
# include <stdio.h>
int main() {
char operator;
int a,b;
printf("Enter the operator (+, -, *, /): ");
scanf("%c", &operator);
printf("Enter two number and seperate them with space: ");
scanf("%lf %lf",&a, &b);
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("% 2lf - %.2lf = % 2lf",a, b, a - b);
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
很抱歉,如果问题在这里。
答案的链接也将受到赞赏!
干杯!
答案 0 :(得分:1)
我已经进行了评论中讨论的更正
#include <stdio.h>
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
printf("%.2lf / %.2lf = %.2lf",a, b, a / b);
break;
default:
printf("Error!");
}
return 0;
}
答案 1 :(得分:0)
已更新:
我在资料夹资料夹中找到了我最古老的代码,也许对您有帮助。肯定可以。
char operator;
printf("Enter the Operation in ( * , / , - , + )");
scanf("%s",&operator);
if(operator!='+' || operator!='-' || operator!='*' || operator!='/')
{
return 0;
}
答案 2 :(得分:0)
我知道了。这比我想的要容易。 所以正确的代码,我将在注释中回答。 #include
int main(void) { // correct definition
char operator;
double a,b; // correct type
printf("Enter the operator (+, -, *, /): ");
if(scanf("%c", &operator) != 1) { // add error check
puts("Bad operator entered");
return 1;
}
printf("Enter two number and seperate them with space: ");
if(scanf("%lf %lf",&a, &b) != 2) { // add error check
puts("Bad value(s) entered");
return 1;
}
switch(operator)
{
case '+':
printf("%.2lf + %.2lf = %.2lf",a, b, a + b);
break;
case '-':
printf("%.2lf - %.2lf = % 2lf",a, b, a - b); // corrected typo
break;
case '*':
printf("%.2lf * %.2lf = %.2lf",a, b, a * b);
break;
case '/':
if(b!=0){ //added an if-sentence
printf("%.2lf / %.2lf = %.2lf\n",a, b,
a / b);
}
else
printf("Can't divide by zero\n");
break;
default:
printf("Error!");
}
return 0;
}
基本上,我只是对case('/')使用if语句。