本文实例为大家分享了C++正整数的四则运算表达式的具体代码,供大家参考,具体内容如下
设计程序,用户输入一个正整数的四则运算表达式的字符串,输出相应的运算结果。
(假设每个字符串表达式只有一个运算符,且是合法的)
如:
输入字符串23+54,则输出77,如果是整数除法,只需输出商即可。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
#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;
}
|
关键:
- 字符串转数字
- 检测空格
- 提取字符串中的运算符号
- 排除除以0的错误
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持服务器之家。
原文链接:https://blog.csdn.net/weixin_43338264/article/details/88925019