我不明白为什么在逐行调试过程中,它甚至没有进入函数时总是抛出异常。
我的代码:
#include <iostream>
#include <string>
#include <sstream>
#include <stack>
#define LENGTH 10
using namespace std;
bool is_number(const std::string& s)
{
try
{
std::stod(s);
}
catch (...)
{
return false;
}
return true;
}
int countAfterComma(double num) {
stringstream s;
s << num;
int pos = s.str().find('.');
if (pos != string::npos) return s.str().size() - 1 - pos;
return 0;
}
int countBeforeComma(double num) {
string str = to_string(num);
int count = 0;
while (str[count] != '.') count++;
return count;
}
double calcOpz(string opz, stack <double> Buff) {
int length = opz.length();
string lexems[LENGTH];
int j = 0;
for (int i = 0; i < length; i++) {
if (opz[i] != ' ')
lexems[j] += opz[i];
else j++;
}
for (int i = 0; i < j + 1; i++) {
if (is_number(lexems[i])) Buff.push(stod(lexems[i]));
else {
double num1 = Buff.top();
Buff.pop();
double num2 = Buff.top();
Buff.pop();
if (lexems[i] == "+") Buff.push(num1 + num2);
else if (lexems[i] == "-") Buff.push(num2 - num1);
else if (lexems[i] == "*") Buff.push(num1 * num2);
else if (lexems[i] == "^") {
if (floor(num1) != num1) {
if (num2 < 0) throw "Your base num less than zero";
//int test = countBeforeComma(num1);
int _comma = countAfterComma(num1);
int numerator = num1 * pow(10, _comma);
int denominator = pow(10, _comma + countBeforeComma(num1));
Buff.push(pow(pow(num2, 1.0 / denominator), numerator));
}
else {
Buff.push(pow(num2, num1));
}
}
else Buff.push(num2 / num1);
}
}
return Buff.top();
}
int main()
{
stack<double> buff;
cout << calcOpz("-2 1.5 ^", buff);
}
它发生在这个注释行上:
int _comma = countAfterComma(num1);
Visual Studio 警告我代码错误:
<块引用>答案 0 :(得分:0)
[...] 它甚至没有进入函数。
这是真的,因为 num2 = -2
,字符串 "Your base num less than zero"
被抛出但它没有被捕获,所以不推荐四处抛出字符串。我建议你将它包装在一个实际的异常中并抛出它。
条件如下:
if (lexems[i] == "+") Buff.push(num1 + num2); // false
else if (lexems[i] == "-") Buff.push(num2 - num1); // false
else if (lexems[i] == "*") Buff.push(num1 * num2); // false
else if (lexems[i] == "^") { // true
if (floor(num1) != num1) { // true
if (num2 < 0) throw "Your base num less than zero"; // true
将投掷线更改为:
if (num2 < 0) throw invalid_argument("Your base num less than zero");
并在 main 中捕获它:
int main()
{
stack<double> buff;
string str = "-2 1.5 ^";
try {
cout << calcOpz(str, buff);
}
catch (exception& e)
{
cout << e.what(); // or whatever you need to do
}
}
会让问题变得明显。
Visual Studio 实际上有一些非常好的通用调试功能,根据您的版本好坏,请充分利用它。