Lost, non-functioning if statements in my first program

The program delivers all the values of the expression and the loop correctly. However the if statements do not work. What is wrong with my code and how can I fix it?

CODE:
using namespace std;
int main()


{
double x, y;

cout << "My name is Daniil Aleksandrov, and this is the output of my first program" <<endl <<endl;
cout << "X Value\t\tY Value" << endl <<endl <<endl;


for (x = -4; x<=2.0; x++){

y = (15 * x * x * x - (4 * x +54))/(sqrt(5 * x * x + 1) + 7 * fabs(x - 2.5));

cout << "X is " << x << "\tY is " << y;

if(y = 0)
cout << "\tY is Zero";
cout << endl;

if(y > 0)
cout << "\tY is Positive";
cout << endl;

if(y < 0)
cout << "\tY is Negative";
cout << endl;


}

cout << "\nMy First Program is Complete" <<endl;

return 0;
}

OUTPUT:

My name is Daniil Alek, and this is the output of my first program

X Value Y Value


X is -4 Y is -18.3119


X is -3 Y is -9.8714


X is -2 Y is -4.60056


X is -1 Y is -2.41192


X is 0 Y is -2.91892


X is 1 Y is -3.32059


X is 2 Y is 7.17593



My First Program is Complete

Process returned 0 (0x0) execution time : 0.031 s
Press any key to continue.

if(y = 0)//assignment

should be:

if(y == 0.0) //equality - almost certain to be false

Always use the equality operator in an if statement.

But that is a problem in itself, FP (floating point - includes doubles and floats) numbers are represented as binary fractions, and cannot represent all real numbers. If you specify x as a double number what you get is x +/- a small number (about 1e-16).

For the same reason you should not do this:

for (x = -4; x<=2.0; x++){ // probably executes 8 times not 7

Always use integer values for the conditionals in loops - you can always convert them to double inside the loop.

To make meaningful comparisons with FP numbers, you need the absolute value of a the number with an arbitrary precision (0.001 say). So for comparison with zero you have:

1
2
double Precision = 0.001;
if (abs(x) < Precision) //close enough to zero for us 


http://www.cplusplus.com/reference/cmath/abs/


There is also a value called epsilon which you can use instead of the arbitrary precision.

http://www.cplusplus.com/reference/limits/numeric_limits/



1
2
3
4
5

#include <limits>       // std::numeric_limits
double Precision = std::numeric_limits<double>::epsilon()

if (abs(x) < Precision) {}


Hope this helps & good luck :)


Last edited on
Thank you so much. That cleared it up.
Topic archived. No new replies allowed.