新的CS,新的C语言。请帮助程序需要支持所有+,-,*,/,%函数,并返回用户输入方程的结果。程序应该不断地接受新的输入,直到用户输入空行为止。除了方程的结果外,不应该打印任何输出。
例如投入和产出:
8+2(输入)-用户输入
10 -产出
8-2(输入)-用户输入
6-产出
(输入)-用户输入(程序终止)
提供的提示是使用get()& sscanf()从用户获取输入。
#include <stdio.h>
int main()
{
char equation[10];
int x, y, result;
char eqsign[2];
int switchnum;
gets(equation);
sscanf(equation, "%d %s %d", &x, eqsign, &y);
if (eqsign == '+')
switchnum = 0;
else if (eqsign == '-')
switchnum = 1;
else if (eqsign == '*')
switchnum = 2;
else if (eqsign == '/')
switchnum = 3;
else if (eqsign == '%')
switchnum = 4;
while(equation != "\0")
{
switch(switchnum)
case '0':
result = x + y;
printf("%d", result);
break;
case '1':
result = x - y;
printf("%d", result);
break;
case '2':
result = x * y;
printf("%d", result);
break;
case '3':
result = x / y;
printf("%d", result);
break;
case '4':
result = x % y;
printf("%d", result);
break;
}
return 0;
}我现在的代码没有正确运行,请用C提供任何建议!在如何比较运算符表单输入方面有很多问题。任何帮助都将不胜感激!
发布于 2022-01-29 00:32:49
由于运算符是单个字符,因此不需要对其进行字符串处理。此外,不需要switchnum,因为您可以直接打开运算符值。
#include <stdio.h>
int main()
{
char equation[22];
int x, y, result;
char operator;
if (!fgets(equation,sizeof(equation),stdin)) {
perror("Reading equation");
return -1;
}
if (sscanf(equation, "%d %c %d", &x, &operator, &y) != 3) {
fprintf(stderr,"Invalid equation!\n");
return -2;
}
switch(operator) {
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
case '%':
result = x % y;
break;
default:
fprintf(stderr,"Invalid operator '%c'!\n",operator);
return -3;
}
printf("%d", result);
return 0;
}https://stackoverflow.com/questions/70900335
复制相似问题