簡體   English   中英

C 中的“重復計算器”程序帶有 swtich 大小寫和 while 循環,在第一次編譯后不工作

[英]'Repeating calculator' program in C with swtich case and do while loop, not working after 1st compilation

#include <stdio.h>
int main()
{
    char operator;
    double num1, num2, sum, mult, div, subtract, percentage;
    

    do
    {
        printf("Enter a operator :\n");
        printf("Click '+' for Addition\n");
        printf("Click '-' for Subtraction\n");
        printf("Click '*' for Multiplication\n");
        printf("Click '/' for Division\n");
        printf("Click '%%' for Percentage\n");
        printf("Click '0' for Exit\n");
        scanf("%c", &operator);
        printf("Enter any two numbers\n");
        scanf("%lf%lf", &num1, &num2);

        switch (operator)
        {
        case ('+'):
            sum = num1 + num2;
            printf("The sum of %.2lf and %.2lf is %.2lf\n", num1, num2, sum);
            break;
        case ('-'):
            subtract = num1 - num2;
            printf("The substraction of %.2lf and %.2lf is %.2lf\n", num1, num2, subtract);
            break;
        case ('*'):
            mult = num1 + num2;
            printf("The multiplication of %.2lf and %.2lf is %.2lf\n", num1, num2, mult);
            break;
        case ('/'):
            div = num1 / num2;
            printf("The division of %.2lf and %.2lf is %.2lf\n", num1, num2, div);
            break;
        case ('%'):
            percentage = (num1 / num2) * 100;
            printf("The percentage of %.2lf and %.2lf is %.2lf %%\n", num1, num2, percentage);
            break;
        default:
            printf("Invalid number, try a valid number\n");
        }
    } while (operator!= '0');

    return 0;
}

我嘗試了什么?

  • 我正在嘗試使用 switch case 制作一個重復的計算器程序並執行 while 循環(用於重復相同的程序。)

我在期待什么?

  • 我期待計算器重復並詢問用戶是否要繼續使用計算器。

現實中發生了什么?

  • 在第一次編譯時,一切正常,計算器運行。 但是,在第二次編譯時,程序並沒有掃描'operator'而是直接跳轉到'enter the numbers'

正如Johnny MoppAndreas Wenzel已經回答的那樣,您的scanf("%c", &operator); 調用從scanf("%lf%lf", &num1, &num2);中讀取換行符 ( \n ); 在循環的前一次迭代中運行的。

您可以更改調用以在格式字符串中的%c說明符之前包含一個空格,以允許scanf() function 跳過輸入緩沖區中的任何前導空白字符。

它應該如下所示:

scanf(" %c", &operator);

此外,在乘法計算中,您使用了+運算符而不是*

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM