下面举个例子
假如求解复数的运算这个问题
当我们输入两个复数之后,准备输入操作字符,却发现怎么也输不进去
(附代码,大家可以运行一下试试)
#include <stdio.h>
#include <stdlib.h>
int main()
{
double a,b,c,d,r,i,t;
char op;
printf("Enter the first complex number: ");
scanf("%lf %lf",&a,&b);
printf("Enter the second complex number: ");
scanf("%lf %lf",&c,&d);
fflush(stdin);
printf("Enter a operator: ");
scanf("%c",&op);
switch(op)
{
case'+':
r=a+c;
i=b+d;
break;
case'-':
r=a-c;
i=b-d;
break;
case'*':
r=a*c-b*d;
i=b*c+a*d;
break;
case'/':
t=c*c-d*d;
if(t==0)
{
printf("The denominator is 0.\n");
return 0;
}
r=(a*c+b*d)/t;
i=(b*c-a*d)/t;
break;
default:
printf("Invalidation operator.\n");
return 0;
}
printf("The result is %lf+%lfi\n",r,i);
}
真是让人头疼,不知道哪里出了问题。
原来是因为当输入四个数(两个复数的实部和虚部)a,b,c,d之后,按下回车出现让输入操作字符的提示,此时程序默认你刚刚敲的回车(n)就是你要输入的字符了,之间就提示字符非法然后自动退出程序了。
要解决这个问题,就在提示Enter a operator:前加一个缓冲区处理。 fflush(stdin);
这样它就不会把你敲下的回车当作要输入的字符啦~
下面是复数四则运算代码
#include <stdio.h>
#include <stdlib.h>
int main()
{
double a,b,c,d,r,i,t;
char op;
printf("Enter the first complex number: ");
scanf("%lf %lf",&a,&b);
printf("Enter the second complex number: ");
scanf("%lf %lf",&c,&d);
fflush(stdin);
printf("Enter a operator: ");
scanf("%c",&op);
switch(op)
{
case'+':
r=a+c;
i=b+d;
break;
case'-':
r=a-c;
i=b-d;
break;
case'*':
r=a*c-b*d;
i=b*c+a*d;
break;
case'/':
t=c*c-d*d;
if(t==0)
{
printf("The denominator is 0.\n");
return 0;
}
r=(a*c+b*d)/t;
i=(b*c-a*d)/t;
break;
default:
printf("Invalidation operator.\n");
return 0;
}
printf("The result is %lf+%lfi\n",r,i);
}