以下是使用字符串数组和枚举实现的简单计算器代码:

#include <stdio.h>
#include <string.h>

enum {ADD, SUB, MUL, DIV};

int main() {
    char input[100];
    char *token;
    char *operands[2];
    int operator;
    int result;

    printf("Enter a calculation (e.g. 2 + 3): ");
    fgets(input, sizeof(input), stdin);

    // Split input into tokens based on whitespace
    token = strtok(input, " ");
    for (int i = 0; i < 2; i++) {
        operands[i] = token;
        token = strtok(NULL, " ");
    }
    operator = token[0];

    // Perform calculation
    switch (operator) {
        case '+':
            result = atoi(operands[0]) + atoi(operands[1]);
            break;
        case '-':
            result = atoi(operands[0]) - atoi(operands[1]);
            break;
        case '*':
            result = atoi(operands[0]) * atoi(operands[1]);
            break;
        case '/':
            result = atoi(operands[0]) / atoi(operands[1]);
            break;
        default:
            printf("Invalid operator\n");
            return 1;
    }

    printf("Result: %d\n", result);
    return 0;
}

该程序首先通过 fgets 函数从标准输入中读取一行字符串,然后使用 strtok 函数将字符串拆分为操作数和运算符。运算符被存储为一个字符,而操作数则作为字符串存储在字符串数组中。

最后,程序使用 switch 语句根据运算符执行相应的计算,并将结果打印到控制台。注意,此程序假定输入的操作数都是整数。如果需要进行更复杂的计算,还需要添加更多的代码

C语言用字符串数组和枚举做计算器

原文地址: http://www.cveoy.top/t/topic/eTc6 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录