C语言利用基础知识实现编程题计算器3种写法

C 语言编程题计算器,可以利用学习的编程基础知识实现,分别使用基本的 if-else 结构、switch-case 结构以及函数指针数组来实现。每种方法都有其优缺点,可以根据具体需求和编程经验选择合适的方法来实现简单计算器。

1、使用 if-else 结构实现的简单计算器

#include <stdio.h>

int main() {
    char operator;
    double num1, num2, result;

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

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

    if (operator == '+') {
        result = num1 + num2;
    } else if (operator == '-') {
        result = num1 - num2;
    } else if (operator == '*') {
        result = num1 * num2;
    } else if (operator == '/') {
        if (num2 != 0)
            result = num1 / num2;
        else {
            printf("Error! Division by zero.\n");
            return 1;
        }
    } else {
        printf("Error! 无效操作符.\n");
        return 1;
    }

    printf("结果: %.2lf\n", result);
    return 0;
}

参考文档:

C语言运算符

C语言条件语句(If else)

2、使用 switch-case 结构实现的简单计算器

#include <stdio.h>

int main() {
    char operator;
    double num1, num2, result;

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

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

    switch (operator) {
        case '+':
            result = num1 + num2;
            break;
        case '-':
            result = num1 - num2;
            break;
        case '*':
            result = num1 * num2;
            break;
        case '/':
            if (num2 != 0)
                result = num1 / num2;
            else {
                printf("Error! Division by zero.\n");
                return 1;
            }
            break;
        default:
            printf("Error! 无效操作符.\n");
            return 1;
    }

    printf("结果: %.2lf\n", result);
    return 0;
}

参考文档C语言 switch case 语句

3、使用函数指针数组实现的简单计算器

#include <stdio.h>

double add(double a, double b) {
    return a + b;
}

double subtract(double a, double b) {
    return a - b;
}

double multiply(double a, double b) {
    return a * b;
}

double divide(double a, double b) {
    if (b != 0)
        return a / b;
    else {
        printf("Error! Division by zero.\n");
        return 0;
    }
}

int main() {
    char operator;
    double num1, num2, result;
    double (*operation[256])(double, double) = { NULL };

    operation['+'] = add;
    operation['-'] = subtract;
    operation['*'] = multiply;
    operation['/'] = divide;

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

    if (operation[(int)operator] == NULL) {
        printf("Error! Invalid operator.\n");
        return 1;
    }

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

    result = operation[(int)operator](num1, num2);
    printf("结果: %.2lf\n", result);

    return 0;
}

参考文档:

C语言指针

C语言指针变量的加减及比较

C语言指针数组

C语言函数指针和指针函数

推荐阅读
cjavapy编程之路首页