关于c语言中 输入字符输不进去的问题(复数四则运算)

下面举个例子

假如求解复数的运算这个问题

当我们输入两个复数之后,准备输入操作字符,却发现怎么也输不进去

(附代码,大家可以运行一下试试)

#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);
}

 

  • 4
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值