我的代码应该能够在一个文本文件中使用;
字符打印多个不同的方程式,导致方程停止并转到下一行,^
字符取数字平方。但是,代码只打印一个等式然后停止。有人告诉我,我需要在已经建立的循环上循环。我不知道怎么能这样做。谢谢。
INPUT
5^ + 5 - 4^; 2 - 1; 1 + 5^ + 2;
我的输出
14
我的代码
#include <iostream>
#include <math.h>
#include <fstream>
using namespace std;
char op;
int result, operand;
int readnumber();
int readnumber()
{
int val;
cin >> val;
if (cin.peek() == '^')
{ // found ^
val *= val;
cin.ignore();
}
return val;
}
int main() {
result = readnumber();
while (cin >> op) {
if (op == ';') {
cout << result << endl;
cin >> result;
}
operand = readnumber();
if (op == '+') {
result += operand;
}
if (op == '-') {
result -= operand;
}
}
return 0;
}
您打算在打印结果后尝试读取数字(cin >> result;
)。通过删除该行,我可以添加更多项目(虽然结果似乎不正确)。