基于C语言实现的简单手持计算器程序示例


#include <stdio.h>
#include <stdlib.h>

#define MAX_INPUT_SIZE 100 // 最大输入长度

int main()
{
    char input[MAX_INPUT_SIZE]; // 储存用户输入
    double result = 0.0; // 计算结果
    char operator = '+'; // 默认运算符为'+'

    printf("Simple Calculator\n");
    printf("Supported operators: + - * / C A\n");
    printf("Enter your calculation, then press '=' to get result.\n");

    while (1) {
        printf("Input: ");
        fgets(input, MAX_INPUT_SIZE, stdin); // 从用户输入中读取一行

        // 处理操作符
        switch (input[0]) {
            case '+':
            case '-':
            case '*':
            case '/':
                operator = input[0];
                break;
            case '=':
                printf("Result: %.2lf\n", result); // 将结果输出至两位小数
                break;
            case 'C':
                result = 0.0;
                break;
            case 'A':
                result = 0.0;
                operator = '+';
                break;
            default:
                // 如果用户输入了数字,则进行运算
                if ((input[0] >= '0' && input[0] <= '9') || input[0] == '.') // 数字和小数点
                    result = atof(input); // 将字符串转换为浮点数
                else
                    printf("Invalid input.\n");
                break;
        }

        // 根据运算符进行计算
        switch (operator) {
            case '+':
                result += atof(input);
                break;
            case '-':
                result -= atof(input);
                break;
            case '*':
                result *= atof(input);
                break;
            case '/':
                result /= atof(input);
                break;
        }
    }

    return 0;
}
 

示例测试:

```
Simple Calculator
Supported operators: + - * / C A
Enter your calculation, then press '=' to get result.
Input: 12.3+2-12+5=
Result: 7.30
```

评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值