用c++ 将一个含有‘+’,‘-’、‘*’的字符串分解计算然后转换成整数,如果字符串不规则就返回0。例如‘112+58-98+65-147+83’结果为73;‘24-58-147+3’结果为-178;‘29+ab-87’结果为0。
时间: 2023-05-20 14:05:16 浏览: 64
以下是用C语言实现的代码:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <ctype.h>
int calculate(char *str) {
int result = 0;
char *token = strtok(str, " -*");
while (token != NULL) {
if (isdigit(token[0])) {
int num = atoi(token);
if (result == 0) {
result = num;
} else if (strchr(str, '-') != NULL) {
result -= num;
} else {
result += num;
}
} else {
return 0;
}
token = strtok(NULL, " -*");
}
return result;
}
int main() {
char str[100];
printf("请输入一个含有‘ ’,‘-’、‘*’的字符串:");
fgets(str, sizeof(str), stdin);
str[strcspn(str, "\n")] = '\0';
int result = calculate(str);
printf("结果为:%d\n", result);
return 0;
}
```
输入示例:
```
请输入一个含有‘ ’,‘-’、‘*’的字符串:112 58-98 65-147 83
```
输出示例:
```
结果为:73
```
输入示例:
```
请输入一个含有‘ ’,‘-’、‘*’的字符串:24-58-147 3
```
输出示例:
```
结果为:-178
```
输入示例:
```
请输入一个含有‘ ’,‘-’、‘*’的字符串:29 ab-87
```
输出示例:
```
结果为:0
```
希望这个代码能够帮到你!