27-题目1019:简单计算器

本文探讨了使用栈数据结构处理多行计算的问题,详细分析了现有代码中存在的读取换行错误,并提出了改进方案。通过实例演示了如何正确地使用栈结构进行多行数学表达式的解析与计算。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

http://ac.jobdu.com/status.php?user_id=yy4869

用栈数据结构,但是出错了,对于一行的计算结果是正确的,但是不能进行多行计算,我怀疑是cin不能读换行之类的错误,我也不知道怎么改

#include<stdio.h>
#include<string.h>
#include<fstream>
#include<iostream>
#include<iomanip>
using namespace std;
#define MAX 200

float stack[MAX];
int tail = 0;

int main(){
	int a,algo;
	ifstream cin("data.txt");
	while (cin >> a && a !=0 )
	{
		stack[tail] = (float)a;
		char algo, str;  //algo表示运算符,str表示换行,判断是否结束
		while (cin >> algo >> a)
		{
			if (algo == '+')
				stack[++tail] = (float)a;
			else if (algo == '-')
				stack[++tail] = -(float)a;
			else if (algo == '*')
				stack[tail] = stack[tail] * (float)a;
			else if (algo == '/')
				stack[tail] = stack[tail] / (float)a;
		}
		float result = 0;
		for (int i = 0; i <= tail; i++)
			 result += stack[i];
		cout << setiosflags(ios::fixed) << setprecision(2) << result << endl;
		//char ch = getchar();
	}
	system("pause");
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值