我正在寫一個基於C++控制檯的計算器。問題推浮游物堆棧控制檯計算器
它的工作方式是 - readEquation包含一個迭代器,它讀取總和,並將所有數字放入堆棧。當讀出的方程遇到操作員時,例如 。 '+',它調用add()函數,它帶有兩個參數:add(float topOfStack,nextNumber()); -nextNumber處理BODMAS,如果下一個數字被分割或相乘,它將首先解決這些問題,否則它將返回數字。 - 先前的總和從堆棧彈出,並將加法結果推送到堆棧。
這是我寫到目前爲止的代碼: 根據調試器,我在這一行中得到某種錯誤this->numberStack->push(f);
- 但它並沒有告訴我問題是什麼。我會很感激任何幫助。
感謝
代碼:
#include <iostream>
#include <cstdlib>
#include <sstream>
#include <string>
#include <cmath>
#include <cstring>
#include <stack>
using namespace std;
class Calculator
{
public:
Calculator();
virtual ~Calculator();
void readEquation();
float nextInteger(int position);
string equation;
protected:
float add(float firstNumber, float secondNumber);
float subtract (float firstNumber, float secondNumber);
float multiply (float number, float multiple);
float divide (float numerator, float denominator);
float squareRoot(float number);
float square(float number);
private:
void temporaryPrintStack();
float answer();
stack<float>* numberStack;
};
Calculator::Calculator()
{
//c
}
Calculator::~Calculator()
{
//dtor
}
float Calculator::add(float numOne,float numTwo)
{
return numOne+numTwo;
}
float Calculator::subtract(float numOne,float numTwo)
{
return numOne-numTwo;
}
float Calculator::multiply(float number, float multiple)
{
return number*multiple;
}
float Calculator::divide(float numerator, float denominator)
{
return numerator/denominator;
}
float Calculator::square(float number)
{
return number*number;
}
float Calculator::squareRoot(float number)
{
return 0;
}
float Calculator::answer()
{
return this->numberStack->top();
}
void Calculator::temporaryPrintStack()
{
for(int index = 0; index <= (int) this->numberStack->size();index++)
{
cout<<this->numberStack->top()<<", ";
this->numberStack->pop();
}
}
void Calculator::readEquation()
{
int position=0;
stringstream stringStream;
string::iterator iterator;
for(iterator = this->equation.begin();iterator!=this->equation.end();iterator++,position++)
{
if(*iterator>='0' && *iterator<='9' || *iterator=='.')//can this be replaced by isdigit()?
{
stringStream<<*iterator;
}
if(*iterator=='+')
{
string number;
stringStream>>number;
cout<<number<<" pushed to stack."<<endl;
float f = atof(number.c_str());
this->numberStack->push(f);
//this->numberStack->push(this->add(this->numberStack->top(),this->nextInteger(position)));
this->temporaryPrintStack();
}
if(*iterator=='=')
{
this->answer();
}
}
}
int main()
{
Calculator *c=new Calculator();
std::cout<<"Enter your sum in this form 2+2/1=";
getline(cin,c->equation,'=');
c->readEquation();
system("pause");
delete c;
return 0;
}
這是作業是嗎?標記爲這樣。 –
@Erich Lancaster:您必須更具體地瞭解您所看到的錯誤信息或行爲,而不僅僅是說「出現某種錯誤」。 –