我在RPN calc中实现cmath函数时遇到问题。 我注意到通话的不同行为。 如果我在POW语句中有pow(y,x),我将从表达式中得到0.5作为答案: 2 1 arctan cos pow(正确)。 但是,如果输入以下内容,则使用相同的代码: 3配方8战俘,我收到0(不正确)。.
但是,如果我在pow()调用(pow(x,y))中切换y和x 并输入: 2 1 arctan cos pow我收到0.9(不正确) 如果我输入: 我收到了3则8磅的战利品(正确)。.
我尝试过atan(stack.peek());
,但是返回pow(y,x)
时返回0,而返回pow(x,y);
时返回1。
在我不确定的地方,我的逻辑肯定是错的。谢谢
stack.cpp
int main(int argc, char *argv[]){
HPStack stack;
string line;
while(getline(cin,line)) {
stringstream ss(line);
string token;
while(ss >> token){
if(isdigit(token[0])){
stack.push(atof(token.data()));
} else if (token == "+"){
double x = stack.pop();
double y = stack.pop();
stack.push(y+x);
} else if (token == "-"){
double x = stack.pop();
double y = stack.pop();
stack.push(y-x);
} else if (token == "/"){
double x = stack.pop();
double y = stack.pop();
stack.push(y/x);
} else if (token == "*"){
double x = stack.pop();
double y = stack.pop();
stack.push(y*x);
} else if (token == "COS"){
stack.push(cos(stack.peek()));
} else if (token == "ARCTAN"){
double x = stack.pop();
double y = stack.pop();
stack.push(atan2(x,y));
else if (token == "RECIP"){
double x = stack.peek();
double y = stack.peek();
double recip = 1/y;
stack.push(recip);
} else if (token == "POW"){
double x = stack.pop();
double y = stack.pop();
double sum = pow(y,x);
double answer = (int)(sum*10.0)/10.0;
stack.push(answer);
}
}
cout << stack.peek() << endl;
}
return 0;
}
HPStack.h
#ifndef HPSTACK_H_
#define HPSTACK_H_
class HPStack {
public:
void push(double value);
double pop();
double peek();
private:
double x=0.0,y=0.0,z=0.0,t=0.0;
};
#endif
HPStack.cpp
#include "HPStack.h"
void HPStack::push(double value){
t = z;
z = y;
y = x;
x = value;
}
double HPStack::pop(){
double out;
out = x;
x = y;
y = z;
z = t;
return out;
}
double HPStack::peek(){
return x;
}