时间:2021-03-23 09:33:39 | 栏目:C代码 | 点击:次
本文实例为大家分享了C++正整数的四则运算表达式的具体代码,供大家参考,具体内容如下
设计程序,用户输入一个正整数的四则运算表达式的字符串,输出相应的运算结果。
(假设每个字符串表达式只有一个运算符,且是合法的)
如:
输入字符串23+54,则输出77,如果是整数除法,只需输出商即可。
#include <iostream> #include <cstdio> using namespace std; int main() { int i, j, k, len = 0, lenf = 0, lenl = 0, op = 0, z = 0, y = 0, sum = 0; char algorithm[100], f[50] = {0}, l[50] = {0}; cout << "input an expression with one of the four fundamental operations: "; gets(algorithm); //计算初始字符串长度 for (i = 0; algorithm[i] != '\0'; ++i) { len += 1; } //提取运算符号前的字符串 for (j = 0; ('0' <= algorithm[j] && algorithm[j] <= '9') || algorithm[j] == ' '; ++j) { f[j] = algorithm[j]; } //判断运算符号 if (algorithm[j] == '+')op = 1; if (algorithm[j] == '-')op = 2; if (algorithm[j] == '*')op = 3; if (algorithm[j] == '/')op = 4; while (algorithm[j + 1] == ' ')++j; //提取运算符号后的字符串 for (k = j + 1; algorithm[k] != '\0'; ++k) { l[k - j - 1] = algorithm[k]; } //计算两个被提取出来的字符串长度 for (i = 0; f[i] != '\0'; ++i) { lenf += 1; } for (i = 0; l[i] != '\0'; ++i) { lenl += 1; } //把字符串转换为数字 for (i = 0; i < lenf; ++i) { if (f[i] == ' ') continue;//遇到空格后跳过 else z = z * 10 + f[i] - '0'; } for (i = 0; i < lenl; ++i) { if (l[i] == ' ')continue;//遇到空格后跳过 else y = y * 10 + l[i] - '0'; } //判断运算类型 switch (op) { case 4: { if (y == 0) {//排除非法除0操作 cout << z << " / 0: Error !" << endl; } else { cout << z << " / " << y << " = " << z / y << endl; } } default: { switch (op) { case 1: cout << z << " + " << y << " = " << z + y << endl; break; case 2: cout << z << " - " << y << " = " << z - y << endl; break; case 3: cout << z << " * " << y << " = " << z * y << endl; break; default: break; } } } return 0; }
关键: