本文目录一览:
C语言如何实现判断用户输入的算式结果正确?
将用户输入的算式存在字符串中,然后将字符串中的字符转换成对应的数字和符号,自己算一遍。如果对,则告诉用户对,如果错,则告诉用户错。
用C语言判断加减算式的结果对与错时遇到问题。
浮点数有误差,换成以下的代码:
#includestdio.h
#includemath.h
#define THRESHOLD 1e-6
int main()
{
double a;
double b = 4.56, c = 7.32;
printf("%f+%f=", b, c);
scanf("%lf", a);
if (fabs(b+c-a)THRESHOLD)
printf("OK\n");
else
printf("Wrong\n");
}
c语言简单程序 判断算式的正确性
#include stdio.h
#include string.h
main()
{
char buff[256],*pchar;
int a,b,c,i,j;
do{
if(!gets(buff)) {printf("Error when gets\n"); return;}
else if(!buff[0]) gets(buff);
if(sscanf(buff,"%d",a)1) {printf("Syntax error\n"); return;}
for(i=0,c=strlen(buff);ic;i++)
if(buff[i]=='+'||buff[i]=='-'||buff[i]=='*'||buff[i]=='/')
break;
pchar = buff+i+1;
if(sscanf(pchar,"%d",b)1) { printf("Syntax error\n"); return;}
for(j=i+1;jc;j++)
if(buff[j]=='=')
break;
pchar = buff+j+1;
if(sscanf(pchar,"%d",c)1) { printf("Syntax error\n"); return;}
switch (buff[i])
{
case '+':
if(a+b==c) printf("Correct\n");
else printf("Incorrect\n");
break;
case '-':
if(a-b==c) printf("Correct\n");
else printf("Incorrect\n");
break;
case '*':
if(a*b==c) printf("Correct\n");
else printf("Incorrect\n");
break;
case '/':
if(c*b==a) printf("Correct\n");
else printf("Incorrect\n");
break;
}
printf("Continue?(y/n)\n");
} while('y'==getchar());
}