字符串实现四则运算

能够将普通的字符串转为四则运算并计算出结果,如:“1+2*3.4”

public static decimal GetStringDecimalCompute(string str)

        {
            decimal dbReturn = 0;
            try
            {
                string strTemp = new DataTable().Compute(str, string.Empty).ToString();
                if (decimal.TryParse(strTemp, out dbReturn))
                {
                    dbReturn = decimal.Parse(strTemp);// Math.Round(, idecimals);
                }
            }
            catch (Exception exp)
            {
                return 0;
            }
            return dbReturn;
        }
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
以下是一个简单的实现,可以计算两个数字之间的加、减、乘、除运算,支持整数和浮点数: ```c #include <stdio.h> #include <stdlib.h> #include <string.h> #include <ctype.h> #define MAX_LENGTH 100 /* 定义运算符的优先级 */ typedef enum { ADD, SUB, MUL, DIV } Operator; /* 判断字符是否为运算符 */ int is_operator(char c) { return c == '+' || c == '-' || c == '*' || c == '/'; } /* 获取运算符的优先级 */ int get_priority(Operator op) { switch (op) { case ADD: case SUB: return 1; case MUL: case DIV: return 2; } } /* 计算两数之间的四则运算 */ double calculate(double a, double b, Operator op) { switch (op) { case ADD: return a + b; case SUB: return a - b; case MUL: return a * b; case DIV: return a / b; } } /* 计算表达式的值 */ double evaluate(char *expr) { char *ptr = expr; Operator op_stack[MAX_LENGTH]; double num_stack[MAX_LENGTH]; int op_top = -1, num_top = -1; while (*ptr) { /* 如果是数字,将其转换为实数并入栈 */ if (isdigit(*ptr) || *ptr == '.') { double num = atof(ptr); num_stack[++num_top] = num; /* 跳过数字 */ while (isdigit(*ptr) || *ptr == '.') { ptr++; } } /* 如果是运算符 */ else if (is_operator(*ptr)) { Operator op; switch (*ptr) { case '+': op = ADD; break; case '-': op = SUB; break; case '*': op = MUL; break; case '/': op = DIV; break; } /* 将栈中优先级高于等于该运算符的运算符出栈,并计算结果入栈 */ while (op_top >= 0 && get_priority(op_stack[op_top]) >= get_priority(op)) { Operator top_op = op_stack[op_top--]; double b = num_stack[num_top--]; double a = num_stack[num_top--]; num_stack[++num_top] = calculate(a, b, top_op); } /* 将该运算符入栈 */ op_stack[++op_top] = op; ptr++; } /* 如果是空格,跳过 */ else if (*ptr == ' ') { ptr++; } /* 如果是其他字符,报错并退出 */ else { printf("Error: unsupported character '%c'\n", *ptr); exit(1); } } /* 将剩余的运算符出栈并计算结果 */ while (op_top >= 0) { Operator top_op = op_stack[op_top--]; double b = num_stack[num_top--]; double a = num_stack[num_top--]; num_stack[++num_top] = calculate(a, b, top_op); } /* 返回最终结果 */ return num_stack[num_top]; } int main() { char expr[MAX_LENGTH]; printf("请输入表达式:\n"); fgets(expr, MAX_LENGTH, stdin); printf("计算结果为:%.2f\n", evaluate(expr)); return 0; } ``` 这个实现并不完善,还有很多可以改进的地方,例如支持括号、更完善的错误处理等等。但是它可以作为一个入门级的示例,帮助你了解字符串四则运算计算的基本思路。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值