C 语言范例 - 实现简单的计算器

实现加减乘除计算

/**
 * file: main.c
 * author: 简单教程(www.twle.cn)
 */

# include <stdio.h>

int main() {

    char operator;
    double num1,num2;

    printf("输入操作符 (+, -, *,): ");
    scanf("%c", &operator);

    printf("输入两个数字: ");
    scanf("%lf %lf",&num1, &num2);

    switch(operator)
    {
        case '+':
            printf("%.1lf + %.1lf = %.1lf",num1, num2, num1 + num2);
            break;

        case '-':
            printf("%.1lf - %.1lf = %.1lf",num1, num2, num1 - num2);
            break;

        case '*':
            printf("%.1lf * %.1lf = %.1lf",num1, num2, num1 * num2);
            break;

        case '/':
            printf("%.1lf / %.1lf = %.1lf",num1, num2, num1 / num2);
            break;

        default:
            printf("Error! operator is not correct");
    }

    printf("\n");

    return 0;
}

编译运行范例,输出结果如下

$ gcc main.c && ./a.out
输入操作符 (+, -, *,): *
输入两个数字: 22
33
22.0 * 33.0 = 726.0

C 语言范例

关于   |   FAQ   |   我们的愿景   |   广告投放   |  博客

  简单教程,简单编程 - IT 入门首选站

Copyright © 2013-2022 简单教程 twle.cn All Rights Reserved.