苦苦挣扎着编写一个简单的计算器

时间:2015-11-10 15:26:14

标签: c switch-statement calculator break

我正在尝试编写一个简单的计算器。
这是我的代码:

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

int main(void) { 

char operator = 0;
float num1 = 0.0;
float num2 = 0.0;
float sol = 0.0;


while (operator != 'q') {

    printf("Operator: ");
    scanf("%c", &operator);
    printf("First Number: ");
    scanf("%f", &num1);
    printf("Second Number: ");
    scanf("%f", &num2);

    switch (operator)
    {
    case '+': sol = num1 + num2; break;
    case '-': sol = num1 - num2; break;
    case '*': sol = num1 * num2; break;
    case '/': sol = num1 / num2; break;
    case 'q': printf("Finished!"); exit(0);
    default: printf("Error!"); exit(0);
    }

    printf("The solution is: %.2f\n\n", sol); 
}

return 0;
}

所以对我来说代码很好。正如你所看到的那样,我用一个while循环来做这件事,让你计算直到你输入&#39; q&#39;作为运营商。循环的第一次运行工作正常,但它变得令人毛骨悚然(我的控制台):

Operator: +
First Number: 5
Second Number: 4
The solution is: 9.00

Operator: First Number:

为什么程序不允许我在第二次循环运行中输入运算符?

2 个答案:

答案 0 :(得分:6)

大多数使用scanf的格式说明符都会跳过前导空格。 scanf("%f", &num2);没有 第一次迭代结束时scanf("%c", &operator);在输入缓冲区中留下换行符 在第二次迭代开始时%c,读取换行符并继续 在scanf(" %c", &operator);中使用%c之前的空格将允许Sub test() For i = 25 to 30 Range(Cells(i,1),Cells(i,19)).Copy Range(Cells(i,20),Cells(i,39)).PasteSpecial xlPasteValues Next i End Sub 跳过前导空格并捕获运算符。

答案 1 :(得分:0)

您应该检查scanf是否有错误:

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

int main(void) {

    char operator = 0;
    float num1 = 0.0;
    float num2 = 0.0;
    float sol = 0.0;

    while (operator != 'q') {

        printf("Operator: ");
        if((scanf(" %c", &operator)) != 1){
            printf("Error, Fix it!\n");
            exit(1);
        }

        printf("First Number: ");
        if((scanf("%f", &num1)) != 1){
            printf("Error, Fix it!\n");
            exit(1);
        }

        printf("Second Number: ");
        if((scanf("%f", &num2)) != 1){
            printf("Error, Fix it!\n");
            exit(1);
        }

        switch (operator){
            case '+': sol = num1 + num2; break;
            case '-': sol = num1 - num2; break;
            case '*': sol = num1 * num2; break;
            case '/': sol = num1 / num2; break;
            case 'q': printf("Finished!"); exit(0);
            default: printf("Error!"); exit(0);
        }

        printf("The solution is: %.2f\n\n", sol);
    }

    return 0;
}

正如您所看到的,我已将scanf("%c", &operator);更改为此scanf(" %c", &operator);,以使scanf忽略(跳过)Whitespace