#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
void scan_data(char&, float&);
void do_next_op(char, float, float&);
int main()
{
float accumulator; //value on the left of the equation
float operand; //value on the right
char op = ' ';
while(op != 'q')
{
scan_data(op, operand); //retrieve the operator and operand from the file
do_next_op(op, operand, accumulator);
if (op != 'q')
{
cout << "Result so far is " << setprecision(1) << fixed << accumulator;
}
else
{
return 1;
}
}
return 0;
}
void scan_data(char& op, float& operand)
{
cin >> op >> operand;
}
void do_next_op(char op, float operand, float& accumulator)
{
if (op == '+')
{
accumulator = accumulator + operand;
}
else if (op == '-')
{
accumulator = accumulator - operand;
}
else if (op == '*')
{
accumulator = accumulator * operand;
}
else if (op == '/')
{
if (operand != 0)
{
accumulator = accumulator / operand;
cout << "Result so far is " << fixed << setprecision(1) << accumulator << endl;
}
else
{
cout << "Error: Division by zero";
}
}
else if (op == '^')
{
accumulator = pow(accumulator, operand);
}
else if (op == 'q')
{
cout << "Final result is " << accumulator << ".";
}
else
{
cout << "Error: invalid operator" << endl;
}
}
虽然xcode没有告诉我语法有什么问题,但我无法运行。你们能指出我如何让它运行的正确方向吗?
答案 0 :(得分:1)
语法没有错,因为我能够在VS2013上运行它。您需要初始化累加器(浮点累加器(0))以获得任何有意义的计算。
您还应添加一些内容以提示用户在scan_data函数中输入操作数和操作数。
最后你应该在用户输入之后测试q,而不是强迫他们输入'q'然后输入另一个数字,这取决于你对程序的用途。
void scan_data(char& op, float& operand)
{
cin >> op;
if(op == 'q')
return;
cin >> operand;
}