C語言練手專案--C 語言製作簡單計算器

worthsen發表於2018-12-04

一、需求

使用 C 語言做一個簡單的計算器,能執行加、減、乘、除操作

二、實現

1、思路

(1)標準輸入到str中
(2)將str中運算子和數值分別記錄在兩個陣列中
(3)然後逐次對每個運算子和相關的左值和右值進行運算
(4)將最後的結果輸出

2、程式碼

/*
 * Author: sen
 * Date: 2018-12-04
 */

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

#define SUM 10
#define MAX 100
typedef enum {
    false, true        
} bool;

float operate(float, float, char);

int main()
{
    printf("************運算器************\n");
    float value[SUM];
    char operators[SUM];
    char str[MAX];
    int valueLen, operatorsLen;
    valueLen = operatorsLen = 0;
    if (fgets(str, MAX, stdin) != NULL) {
        int length = strlen(str) - 1;
        if (str[length - 1] != '=') { 
            printf("please input '=' at the end\n");
        } else {
            int start = 0;
            for (int i = 0; i < length; i++) {
                bool flag = false;
                switch (str[i]) {
                    case '+': 
                        flag = true;
                        operators[operatorsLen++] = '+';
                        break;
                    case '-': 
                        flag = true;
                        operators[operatorsLen++] = '-';
                        break;
                    case '*': 
                        flag = true;
                        operators[operatorsLen++] = '*';
                        break;
                    case '/': 
                        flag = true;
                        operators[operatorsLen++] = '/';
                        break;
                    case '=':
                        flag = true;
                        break;
                    default:
                        break;
                }
                if (flag) {
                    char valueTmp[MAX];
                    for (int j = 0; j <= (i - start + 1); j++) {
                        valueTmp[j] = str[start++];
                    }
                    value[valueLen++] = atof(valueTmp);
                    start = i + 1;
                } 
                flag = false;
            }
        }
    } else {
        printf("please restart!\n");
    }

    float leftValue = value[0];
    int  count = 0;
    while (count < operatorsLen) {
        leftValue = operate(leftValue, value[count + 1], operators[count]);
        count++;
    } 
    printf("The result is: %2.2f\n", leftValue);

    return 0;
}

float operate(float num1, float num2, char symbol)
{
    switch (symbol) {
        case '+':
            return num1 + num2;
            break;
        case '-':
            return num1 - num2;
            break;
        case '*':
            return num1 * num2;
            break;
        case '/':
            return num1 / num2;
            break;
        default:
            printf("Error,please restart!\n");
            return 0;
            break;
    }
}

3、執行結果

在這裡插入圖片描述

三、參考連結

1、C 語言製作簡單計算器

相關文章