I am having an issue with implementing cmath functions within an RPN calc.
I am noticing different behaviours of my calls. If I have pow(y,x) in the POW statement I receive 0.5 as my answer from the expression:
2 1 arctan cos pow (correct)..
But then using the same code if I enter:
3 recip 8 pow I receive 0 (incorrect)..
However, If I switch the y and x in the pow() call (pow(x,y)) and enter:
2 1 arctan cos pow I receive 0.9 (incorrect)
and if I enter:
3 recip 8 pow I receive 2 (correct)..
I have tried atan(stack.peek()); but that returns 0 with pow(y,x) and 1 with pow(x,y);
My logic must be wrong somewhere I am just unsure.. Thankyou
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;
}
Related
I am writing a calculator program in c++ , and I met two problems .
After I calculate 1 calculation questions , I only need to press enter ,then the program will output the last number in the previous calculation .
There are some incorrect answer , like " 7 / 9 / 10 * 1 * 4 / 6 - 3 * 9 - 8 - 7 " , the output should be -41.95 , but my answer is -11.95 .And I can't find what's wrong with my code.
The cin problem has been fixed when I use if(cin.get()!='\n')break;
And At the bottom there is a correct code of others .
my code use istringstream
#include<iostream>
#include<string>
#include<sstream>
#include<stack>
#include<iomanip>
using namespace std;
int priority(char op) {
if (op == '+' || op == '-') return 1;
else return 2;
}
double calculate(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x * y;
return x / y;
}
int main() {
int n;
char op;
stack<double> nums;
stack<char> ops;
string a;
int count = 0;
while (getline(cin, a)) {
count++;
int allNum = 0;
int allzero = 0;
allNum++;
istringstream b(a);
b >> n;
if (n == 0) allzero++;
nums.push(n);
while (b >> op >> n) {
if (op == '\n') break;
allNum++;
if (n == 0) allzero++;
if (!ops.empty() && priority(op) <= priority(ops.top())) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
ops.push(op);
nums.push(n);
}
while (!ops.empty()) {
double y = nums.top();
nums.pop();
double x = nums.top();
nums.pop();
char tem = ops.top();
ops.pop();
double new_num = calculate(x, y, tem);
nums.push(new_num);
}
if (allzero != allNum) cout<< fixed << setprecision(2) << nums.top() << endl;
b.clear();
nums.pop();
}
}
this is the code I find on the internet
I learned the method from here , the biggest differentenss is that he use C ,and I use C++ .But his result is right .
#include <iostream>
#include <cstdio>
#include <cstring>
#include<stack>
using namespace std;
int P(char c)
{
if (c == '+' || c == '-') return 1;
return 2;
}
double Ans(double x, double y, char c)
{
if (c == '+') return x + y;
if (c == '-') return x - y;
if (c == '*')return x*y;
return x / y;
}
int main() {
int n;
while (scanf("%d",&n)!=EOF)
{
char c = getchar();
if (c=='\n'&&n == 0)break;
stack<char> op;
stack<double>num;
num.push(n);
while (true)
{
scanf("%c %d", &c, &n);
char k = getchar();
while (!op.empty()&&P(c)<=P(op.top()))
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
op.push(c);
num.push(n);
if (k == '\n')break;
}
while (!op.empty())
{
char t = op.top();
op.pop();
double y = num.top();
num.pop();
double x = num.top();
num.pop();
double ans = Ans(x, y, t);
num.push(ans);
}
printf("%.2f\n", num.top());
}
return 0;
}
I am doing a code chef practice prblem https://www.codechef.com/problems/CIELAB in easy category. But my solution is not working. The submit screen is showing : Status wrong Answer
#include <iostream>
using namespace std;
int input ();
int difference (int, int);
int calculateWrongAns (int);
int main()
{
int num1;
int num2;
num1 = input();
num2 = input();
int actualAns = difference(num1, num2);
int res = calculateWrongAns(actualAns);
cout << res;
return 0;
}
int input () {
int x;
cin >> x;
return x;
}
int difference (int x, int y) {
if (x > y) {
return x - y;
} else if (x < y) {
return y - x;
} else {
return 0;
}
}
int calculateWrongAns (int actualAns) {
int lastNumber = actualAns % 10;
int otherNumbers = actualAns / 10;
int res;
if (otherNumbers != 0) {
res = (otherNumbers * 10) + (lastNumber == 1 ? 2 : lastNumber - 1);
} else {
res = lastNumber == 1 ? 2 : lastNumber - 1;
}
return res;
}
Thanks in advance.
The line
res = lastNumber == 1 ? 2 : lastNumber - 1;
is wrong. You are splitting the result in last digit and other digits. If the last digit is 1, you are changing it to 2. If it not 1, you are subtracting 1. That means, if the result is 30, you are subtracting 1. The new result is 29. Two digits differ. That's not correct. You could use
int calculateWrongAns (int actualAns) {
return (actualAns % 10) == 0 ? actualAns + 1 : actualAns - 1;
}
While I was writing a c++ program I stuck on a problem. In brief, my program input is one integer which is the number of coordinates that I have to input. And I have an algorithm that calculates the passed distance between all of the points. Here is my algorithm:
#include<iostream>
#include<iomanip>
#include<cmath>
using namespace std;
const double PI = 3.14;
const double rightXLimit = 5;
const double leftXLimit = -5;
const double topYLimit = 2;
const double bottomYLimit = -2;
const int ARR_SIZE = 100;
bool IsPointInRules(double x, double y)
{
if ((x >= leftXLimit && x <= rightXLimit) && (y >= bottomYLimit && y <= topYLimit))
{
return true;
}
return false;
}
double checkLimitsAndDistCalc(double x, double y, double x1, double y1)
{
if (!(IsPointInRules(x, y) || IsPointInRules(x1, y1)))
{
return 0;
}
else if (IsPointInRules(x, y) && (!IsPointInRules(x1, y1)))
{
if (x1 <= leftXLimit)
{
x1 = leftXLimit;
}
if (x1 >= rightXLimit)
{
x1 = rightXLimit;
}
if (y1 <= bottomYLimit)
{
y1 = bottomYLimit;
}
if (y1 >= topYLimit)
{
y1 = topYLimit;
}
}
else if ((!IsPointInRules(x, y)) && IsPointInRules(x1, y1))
{
if (x <= leftXLimit)
{
x = leftXLimit;
}
if (x >= rightXLimit)
{
x = rightXLimit;
}
if (y <= bottomYLimit)
{
y = bottomYLimit;
}
if (y >= topYLimit)
{
y = topYLimit;
}
}
double distance = sqrt(pow(x1 - x, 2) + pow(y1 - y, 2));
double result = ((PI * distance / 2) + distance) / 2;
//cout << setw(3) << x << setw(3) << y << setw(3) << x1 << setw(3) << y1 << " --> " << distance << " --> " << result << endl;
return result;
}
double calculateDistance(double* arrOne, double* arrTwo, int n)
{
double finalResult = 0;
for (int i = 0; i < n - 1; i++)
{
double getDistance = checkLimitsAndDistCalc(arrOne[i], arrTwo[i], arrOne[i + 1], arrTwo[i + 1]);
finalResult += getDistance;
}
return finalResult;
}
int main()
{
double coordsArrX[ARR_SIZE];
double coordsArrY[ARR_SIZE];
int n;
cin >> n;
for (int i = 0; i < n; i++)
{
cin >> coordsArrX[i];
cin >> coordsArrY[i];
}
cout << setprecision(3) << fixed << calculateDistance(coordsArrX, coordsArrY, n) << '\n';
}
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem. Here I tried some auto tests:
The problem is when I enter integers like coordinates the distance is wrong, but when enter double the distance is right and I can not find where is the problem.
That is an incorrect conclusion. The output is same whether you enter the coordinates using what appears to be integers or floating point numbers.
The output obtained using
7
0 0
0 3
-2 4
-1 1
-3 -1
4 1
6 3
is the same as using
7
0.0 0.0
0.0 3.0
-2.0 4.0
-1.0 1.0
-3.0 -1.0
4.0 1.0
6.0 3.0
See the output from using floating point input at http://ideone.com/fxgbga.
It appears that there is something else in your program that is not working as you are expecting.
I'm trying to implement Karatsuba algorithm for multiplication. I'm kinda follow the pseudocode in this wiki page. But I'm always getting this error:
terminated by signal SIGSEGV (Address boundary error)
When I replaced the lines that cause the recursion to happen with something else:
z0 = multiply(a, c);
z1 = multiply(b, d);
z2 = multiply(a+b, c+d);
the error disappeared.
Here's my code:
#include <iostream>
#include <math.h>
long int multiply(int x, int y);
int get_length(int val);
int main()
{
int x = 0, y = 0;
long int result = 0;
std::cout << "Enter x: ";
std::cin >> x;
std::cout << "Enter y: ";
std::cin >> y;
result = multiply(x, y);
std::cout << "Result: " << result << std::endl;
return 0;
}
long int multiply(int x, int y)
{
if(x < 10 || y < 10) {
return x * y;
}
int x_len = get_length(x);
int y_len = get_length(y);
long int z0 = 0 , z1 = 0, z2 = 0;
int a = 0, b = 0, c = 0, d = 0;
a = x / pow(10, x_len);
b = x - (a * pow(10, x_len));
c = y / pow(10, y_len);
d = y - (c * pow(10, y_len));
z0 = multiply(a, c);
z1 = multiply(b, d);
z2 = multiply(a+b, c+d);
return (pow(10, x_len) * z0) + (pow(10, x_len/2) * (z2 - z1 - z0)) + z1;
}
int get_length(int val)
{
int count = 0;
while(val > 0) {
count++;
val /= 10;
}
return count;
}
I found the problem cause.
It was because of these lines:
a = x / pow(10, x_len);
b = x - (a * pow(10, x_len));
c = y / pow(10, y_len);
d = y - (c * pow(10, y_len));
It should be x_len / 2 instead of x_len and the same with y_len. Since it causes the recursion to be infinite.
You are using the pow function to do integer powers. It is not an integer function. Code your own pow function that's suitable for your application. For example:
int pow(int v, int q)
{
int ret = 1;
while (q > 1)
{
ret*=v;
q--;
}
return ret;
}
Make sure to put an int pow(int, int); at the top.
I am writing a simple calculator program. When I try to make it do a division problem that results in a decimal eg: 1/4 or 10/3, it rounds it to the nearest whole number. How could I fix this?
I have a function that takes two numbers (x and y) and an operation (op) , and returns them:
int getAnswer(int x, int op, int y)
int getAnswer(int x, int op, int y)
{
if (op == 1)
return x + y;
if (op == 2)
return x - y;
if (op == 3)
return x * y;
if (op == 4 && y != 0)
return x / y;
if (op == 4 && y == 0)
return 3293; //When 3293 is returned, an error is displayed (not the best way to handle errors, I know)
return 3293;
}
When I input x as 10, for example, y as 3, and op as 4 (for division), it returns 10/3. My main function assigns the returned value to the variable "result". My main:
int main()
{
int input1 = getValueFromUser();
int op = getOperationFromUser();
int input2 = getValueFromUser();
int result = getAnswer(input1, op, input2 );
printResult(result);
std::cin.ignore();
std::cin.get();
return 0;
}
My printResult funcion then prints the result using std::cout, but rather than printing 3.33, it prints 3. So, this leads my to the conclusion that the variable result, has no decimal points. How would I make the variable result have decimal points?
Just in case, my printResult function looks like this:
void printResult(int result)
{
if (result != 3293)
{
std::cout << "The answer is: " << result << std::endl;
}
else
{
std::cout << "ERR: Can't Calc" << std::endl;
}
}
You need the double type to display the divisions correctly. Otherwise it gets rounded to the integer value. For example 4/3 = 1, not 1.33333
double getAnswer(double x, int op, double y)
{
if (op == 1)
return x + y;
if (op == 2)
return x - y;
if (op == 3)
return x * y;
if (op == 4 && y != 0)
return x / y;
if (op == 4 && y == 0)
return 3293; //When 3293 is returned, an error is displayed (not the best way to handle errors, I know)
return 3293;
}
int main()
{
double input1 = getValueFromUser();
int op = getOperationFromUser();
double input2 = getValueFromUser();
double result = getAnswer(input1, op, input2 );
printResult(result);
std::cin.ignore();
std::cin.get();
return 0;
}
void printResult(double result)
{
if (result != 3293)
{
std::cout << "The answer is: " << result << std::endl;
}
else
{
std::cout << "ERR: Can't Calc" << std::endl;
}
}
With a int you cant handle floating point numbers, use float or double.
You can cast your int to float for the division.
float getAnswer(int x, int y)
{
return static_cast<float>(x) / static_cast<float>(y);
}
float result = getAnswer(input1, input2 );
You need to cast your ints to double:
In your getAnswer function:
if (op == 4 && y != 0)
return static_cast<double>(x) / y;
Also make sure your getAnswer function returns double...
your result value also needs to be double, the print function should take a double, etc.