做一个输入检查就好。%lf的输入比较麻烦,感觉得用一个栈,所以改成int 了;c语言对输入输出还是比较严格的#include<stdio.h>
float add(float ,float );
float sub(float ,float );
float cheng(float ,float );
float chu(float ,float );
float calc( float (*fp)(float ,float ),float ,float );
float (*select(char op))(float ,float );
float add(float num1,float num2)
{
return num1 + num2;
}
float sub(float num1,float num2)
{
return num1 - num2;
}
float cheng(float num1,float num2)
{
return num1 * num2;
}
float chu(float num1,float num2)
{
if( num2 != 0 )
{
return num1 / num2;
}else
{
printf("除数为0,无法计算");
}
}
float calc( float (*fp)(float ,float ),float num1,float num2)
{
return (*fp)(num1,num2);
}
float (*select(char op))(float num1,float num2)
{
switch(op)
{
case '+': return add;
case '-': return sub;
case '*': return cheng;
case '/': return chu;
}
}
int main()
{
int num1,num2;
char op,c;
int a=0;
float (*fp)(float,float);
printf("请输入两个数(1+3)\n");
while(1)//输入检查
{
c=getchar();
if(c>='0'&&c<='9')
{
ungetc(c,stdin); //如果是数字,返回输入流
if(a==0) //a为布尔,表示第一个还是第二个数字
scanf("%d",&num1);
else if(a==1)
scanf("%d",&num2);
}
if(c=='+' || c=='-'|| c=='*' || c=='/')
{
op=c; a=1;
}
if(c=='\n')
break;
}
fp = select(op);
printf("%d %c %d = %lf\n", num1, op, num2, calc(fp, num1, num2));
}
|