Skip to content

Latest commit

 

History

History
71 lines (53 loc) · 2.01 KB

File metadata and controls

71 lines (53 loc) · 2.01 KB

C 程序:使用switch...case制作一个简单的计算器

原文: https://www.programiz.com/c-programming/examples/calculator-switch-case

在此示例中,您将学习使用switch语句在 C 编程中创建一个简单的计算器。

要理解此示例,您应该了解以下 C 编程主题:


该程序使用算术运算符+, -, *, /和来自用户的两个操作数。 然后,它根据用户输入的运算符对两个操作数执行计算。


使用switch语句的简单计算器

#include <stdio.h>
int main() {
    char operator;
    double first, second;
    printf("Enter an operator (+, -, *,): ");
    scanf("%c", &operator);
    printf("Enter two operands: ");
    scanf("%lf %lf", &first, &second);

    switch (operator) {
    case '+':
        printf("%.1lf + %.1lf = %.1lf", first, second, first + second);
        break;
    case '-':
        printf("%.1lf - %.1lf = %.1lf", first, second, first - second);
        break;
    case '*':
        printf("%.1lf * %.1lf = %.1lf", first, second, first * second);
        break;
    case '/':
        printf("%.1lf / %.1lf = %.1lf", first, second, first / second);
        break;
        // operator doesn't match any case constant
    default:
        printf("Error! operator is not correct");
    }

    return 0;
} 

输出

Enter an operator (+, -, *,): *
Enter two operands: 1.5
4.5
1.5 * 4.5 = 6.8 

用户输入的*操作符存储在operator中。 并且,将两个操作数1.54.5分别存储在firstsecond中。

由于运算符*case '*':相匹配,因此程序控制跳至

printf("%.1lf * %.1lf = %.1lf", first, second, first * second); 

该语句计算产品并将其显示在屏幕上。

最后,break;语句结束switch语句。