我的程序第二次没有要求操作员

时间:2010-08-09 06:01:59

标签: c

#include<stdio.h>
#include<stdlib.h>   

main(){
    int b,c,r,d;
    char a; 

    while(1){

     printf("Enter the operator\n");

          scanf("%c",&a);

          if(a=='+') d=1;
          if(a=='-') d=2;
          if(a=='&') d=3; 
          if(a=='|') d=4;
          if(a=='.') d=5;

          printf("Enter the operands\n");

          scanf("%d",&b);   
          scanf("%d",&c);

          switch(d){
            case 1:r=c+b;
            break;
            case 2:r=c-b;   
            break;
            case 3:r=c&b;
            break;
            case 4:r=c|b;
            break;
            case 5:exit(0);
            deafult:printf("Enter a valid operator");
        }
        printf("Result = %d\n",r);
    }
}

输出:

Enter the operator
+
Enter the operands
8
7
Result = 15
Enter the operator
Enter the operands

3 个答案:

答案 0 :(得分:2)

由于函数scanf宽度参数“%c”,在第一次循环之后,在行scanf("%d",&c);,如 + ,有一个结束行字符,然后是第二个循环,scanf将 end-line 字符作为输入并将其解析为 a ; 要解决此问题,您可以在scanf("%c");

之后添加scanf("%d",&c);

答案 1 :(得分:2)

scanf("%d",...将读取一个数字(事先跳过空格),但在输入流上保留换行符。 scanf("%c",...将读取第一个字符,并且不会跳过空格。

一个简单的修改是使用

scanf(" %c", &a);

这将告诉scanf跳过字符前的任何空格。

答案 2 :(得分:0)