题解 | #计算表达式#

计算表达式

https://www.nowcoder.com/practice/7b18aa6b7cc14f8eaae6b8acdebf890b

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main(){
	string str;
	while (getline(cin, str)){
		vector<float>vec;
		float num = 0;
		char Presign = '+';
		int n = str.size();
		for (int i = 0; i < n; i++){
			if (isdigit(str[i])){
				num = num * 10 + str[i] - '0';
			}
			if (!isdigit(str[i]) || i == n - 1){
				switch (Presign){
				case'+':
					vec.push_back(num);
					break;
				case'-':
					vec.push_back(-num);
					break;
				case'*':
					vec.back() *= num;
					break;
				default:
					vec.back() /= num;
					break;
				}
				Presign = str[i];
				num = 0;
			}
		}
		float ans = 0;
		for (int i = 0; i < vec.size(); i++){
			ans += vec[i];
		}
		int answer = ans;
		printf("%d\n", answer);
	}
}

全部评论

相关推荐

死在JAVA的王小美:哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈哈,我也是,让我免了一轮,但是硬气拒绝了
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务