在C语言编程的第6章练习#5,“简单”打印“计算器”

时间:2015-08-30 07:28:13

标签: c

C编程的第6章练习#5,由Kochan

  

编写一个程序,作为一个简单的“打印”计算器。该程序应允许用户键入表单的表达式:number operator。该计划应识别以下运营商:+-*/SE
   - S运算符告诉程序将“累加器”设置为输入的数字    - E运算符告诉程序执行将结束。对累加器的内容执行算术运算,其中键入的数字用作第二个操作数。
  以下是“示例运行”,显示程序应如何运作:

   Begin Calculations
        10 S            Set Accumulator to 10 
        = 10.000000     Contents of Accumulator
        2 /             Divide by 2 
        = 5.000000      Contents of Accumulator
        55 -            Subtract 55 
        -50.000000
        100.25 S        Set Accumulator to 100.25 
        = 100.250000
        4 *             Multiply by 4 
        = 401.000000
        0 E             End of program 
        = 401.000000
   End of Calculations.
     

确保程序检测到除零并检查未知运算符。

如果我输入* 2,则会返回inf。这就是我所做的:

#include <stdio.h>

int main(void)
{
    float number1, number2;
    char operator;

    do 
    {
        printf("Enter your number with S sign that set it as your accumulator \n");
        scanf("%f %c", &number1, &operator);

    } while (operator != 'S');


        do 
        {
            printf("Enter your expression with the correct format\n");
            scanf("%f %c", &number2, &operator); 

            if ( operator == '+' || operator == '-' || operator == '/' || operator == '*')
            {
                switch (operator)
                    {
                        case '+':
                            number1 = number1 + number2;
                            printf("=%.6f\n", number1);
                            break;
                        case '-':
                            number1 = number1 - number2;
                            printf("=%.6f\n", number1);
                            break;
                        case '*':
                            number1 = number1 * number2;
                            printf("=%.6f\n", number1);
                            break;
                        case '/':
                            if( number2 == 0) 
                                printf("Division by Zero\n");
                            else
                            {
                                number1 = number1 / number2;
                                printf("%.6f\n", number1);
                            }
                            break;
                        default:
                            printf("not a valid operator\n");
                            break;
                    }
            }
            else
                printf("Retry.\n");

        } while (operator != 'E'); 



    printf("End of Calculations\n");
    return 0;

}

1 个答案:

答案 0 :(得分:1)

对于scanf("%f %c", &number2, &operator);语句,*不是%f的有效字符。 scanf失败,但do块一次又一次地尝试将*读入%f

替换语句
if ( ( scanf("%f %c", &number2, &operator)) != 2) {
    number2 = 1.0f;
    operator = 0;
    scanf ( "%*[^\n]");
}

scanf将返回成功读取的项目数。如果scanf没有返回2,则将值设置为某个适当的值,scanf ( "%*[^\n]);将读取并丢弃缓冲区中不是换行符的所有内容。
number1

的第一次扫描执行类似操作