0

我决定使用代码制作一个计算器,但我的程序无法正常工作。当我输入我的操作数和新数字时,它似乎不会扫描操作数和数字,也不会启动循环。谢谢您的帮助。

#include <stdio.h>
#include <math.h>

float add(float x,float y);
float sub(float x,float y);
float div(float x,float y);
float exp(float x,float y);
float mult(float x,float y);
int main(){

float y,x;
char op;

printf("Type in a number\n");
scanf("%f",&x);
printf("Type in your operand and desired number\n");
scanf("%c",&op);
scanf("%f",&y);


while (!(op=='q')){
    if(op=='+'){
    printf("Your result is %.1f\n",add(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='-'){
    printf("Your result is %.1f\n",sub(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='*'){
    printf("Your result is %.1f\n",mult(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='/'){
    printf("Your result is %.1f\n",div(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }
    else if(op=='^'){
    printf("Your result is %.1f\n",exp(x,y));
    scanf("%c",&op);
    scanf("%f",&y);
    }

}

    printf("Your final result is %.1f\n",x);

        return(0);
}

float add(float x,float y){
return (x+y);

}

float sub(float x,float y){
return (x-y);
}

float div(float x,float y){
return (x/y);
}

float exp(float x,float y){
x=pow(x,y);
return(x);
}
float mult(float x,float y){
return (x*y);
}
4

2 回答 2

1

我认为发生的事情是换行符(return/enter键)在调用后留在输入流中scanf("%f",&y);,这就是在调用中存储为单个字符的内容scanf("%c",&op);

因此,此时您需要丢弃换行符。最简单的方法是在需要读取单个字符时调用scanf("%c",&op); 两次。这应该适用于 Mac 和 Unix。对于 Windows,您可能需要读取该字符3次,因为 Windows 经常将序列 "\r\n" 视为换行符序列

为了可移植性,您可以使用这样的循环:

do {
    op = getchar();
} while (op == '\n' || op == '\r');

并删除scanf("%c",&op);. 这个循环取代了它。


另一种选择是要求scanf自己丢弃初始空白。

scanf(" %c",&op);
//     ^ space

另外,请参阅我对这个非常相似的问题的回答

于 2013-09-05T10:22:35.657 回答
1

when you do

scanf("%c",&op);

you read first char that is in the input buffer. previous scanf left \n char in it, so you read that char.

What you want to do, is to get rid of all what's left behind scanf.

while(getchar()!='\n')
  continue;

That will empty the buffer before you try to read.

Every use of scanf here will leave new line character in the buffer so to get rid of him, use above loop every time you try to read a character from input and you know that newline is there.

于 2013-09-05T10:19:36.283 回答