为什么用这个方法在以样例子串为-*7进入循环后无法继续程序
查看原帖
为什么用这个方法在以样例子串为-*7进入循环后无法继续程序
1050776
peterJr楼主2024/7/20 16:12

打代码打了30min,调了1.5h,如需可自行打开DEBUG开关,了解含义后自动监视程序(也可以自行用软件自带的debug)。请DALAO帮忙看一下 QwQ

#include <iostream>
#include <string>
#include <stack>
#include <vector>
#include <cmath>

#define DEBUG 0

using namespace std;

char c;
string s;
vector<int> dots;
stack<long long> stk;

inline long long convert_string_to_int(string num)
{
	int n = num.size();
	long long ans = 0;
	for (int i = 0, lv = pow(10, num.size() - 1); i < n; ++i)
	{
		ans += (num[i] - '0') * lv;
		lv /= 10;
	}
	return ans;
}

int main()
{
	int k = 0;
	dots.push_back(-1);
	while (cin >> c, c != '@')
	{
		if (c == '.') dots.push_back(k);
		s.push_back(c);
		k++;
	}
	dots.push_back(s.size());

	if (DEBUG)
	{
		cout << dots.size() - 1 << endl;
		for (int i = 0; i < dots.size() - 1; ++i) cout << dots[i] << " " << dots[i + 1] << endl;
	}

	for (int i = 0; i < dots.size() - 1; ++i)
	{
		string sub = s.substr(dots[i] + 1, dots[i + 1] - dots[i] - 1);
		if (DEBUG) cout << sub << " " << dots[i] << " " << dots[i+1] << " " << i << endl;
		bool isnumeric = 1;
		for (int j = 0; j < sub.size(); ++j)
			if (sub[j] < '0' || sub[j] > '9')
			{
				isnumeric = 0;
				break;
			}
		if (isnumeric)
		{
			stk.push(convert_string_to_int(sub));
			continue;
		}

		string subb = sub;
		for (int j = 0; j < sub.size() - 1; ++j)
		{
			if (sub[j] == '+')
			{
				if (DEBUG) cout << "Enter +:";
				int x = stk.top();
				stk.pop();
				int y = stk.top();
				stk.pop();
				if (DEBUG) cout << x << "+" << y << "=" << y + x << endl;
				stk.push(y + x);
				subb.erase(subb.begin(), subb.begin() + 1);
			}
			else if (sub[j] == '-')
			{
				if (DEBUG) cout << "Enter -:";
				int x = stk.top();
				stk.pop();
				int y = stk.top();
				stk.pop();
				if (DEBUG) cout << x << "-" << y << "=" << y - x << endl;
				stk.push(y - x);
				subb.erase(subb.begin(), subb.begin() + 1);
			}
			else if (sub[j] == '*')
			{
				if (DEBUG) cout << "Enter *:";
				int x = stk.top();
				stk.pop();
				int y = stk.top();
				stk.pop();
				if (DEBUG) cout << x << "*" << y << "=" << y * x << endl;
				stk.push(y * x);
				subb.erase(subb.begin(), subb.begin() + 1);
			}
			else if (sub[j] == '/')
			{
				if (DEBUG) cout << "Enter /:";
				int x = stk.top();
				stk.pop();
				int y = stk.top();
				stk.pop();
				if (DEBUG) cout << x << "/" << y << "=" << y / x << endl;
				stk.push(y / x);
				subb.erase(subb.begin(), subb.begin() + 1);
			}
			else
			{
				isnumeric = 1;
				break;
			}

			if (isnumeric)
			{
				stk.push(convert_string_to_int(subb));
				if (DEBUG) cout << stk.top() << endl;
				continue;
			}
		}

		cout << stk.top() << endl;

		return 0;


	}

	return 0;
}
2024/7/20 16:12
加载中...