为了开发一个计算器,我不得不面对这个程序中的一些问题,我已经尝试在开关语句之前对数学运算进行计算。输入“值”和“数学”操作后,打印结果仅提示默认语句上的无效条目。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
int main()
{
// declare and initialise working storage
char function;
int num1, num2, sum, sub, multi, div, remainder;
// prompt user to enter 2 number
printf("Enter numbers and function: ");
scanf("%d%c%d", &num1, &function, &num2);
// calculation
sum = num1 + num2;
sub = num1 - num2;
multi = num1 * num2;
div = num1 / num2;
remainder = num1 % num2;
// print the result
switch(function)
{
case '+':
printf("The sum is %d\n", sum);
break;
case '-':
printf("The subtraction is %d\n", sub);
break;
case '*':
printf("The multiplication is %d\n", multi);
break;
case '/':
if(num2 ==0)
{
printf("Cannot divide by 0!\n");
}
else
{
printf("The div is %d\n", div);
}
break;
case '%':
if(num2 ==0)
{
printf("Cannot divide by 0!\n");
}
else
{
printf("The remainder is %d\n", remainder);
}
break;
default:
printf("Invalid Entry!!!!!\n");
break;
}
return 0;
}发布于 2022-04-15 13:42:41
%c读取字符。空格和换行符也是字符。%d只等待int输入。这就是为什么每次你想提供不同的数字,你必须按返回或空格让程序读取下一个int输入。所以,如果你选择像这样提供你的投入:
1 + 3该方案理解如下:
&num1 = 1 , &num2 = 3, &function = (space)如果您选择这样输入您的角色:
1+3(return)它会正常运行的。但那不是友好的计算器。
你能做的是:
printf("Enter numbers : ");
scanf("%d%d", &num1, &num2);// give 5(space)2 or 5(return)2
scanf(%c,&enter); // reads the newline
printf("Enter function: ");
scanf("%c",&function);https://stackoverflow.com/questions/71883362
复制相似问题