Can anyone tell me why this isn't the right answer?

1
2
double x = sqrt(2); double y = 2;
if (x * x == y) { cout << x; } else { cout << yl }


I thought the answer was sqrt(2) but apparently it's 2. Anyone know why?

Also for doing a trace table for
1
2
3
4
int s = 1
int n = 1
while (s < 10) { s = s + n; }
n++;


Would it be..
Iteration #1--------n = 1--------s = 2
Iteration #2--------n = 2---------s = 4
Iteration #3--------n = 3---------s = 7
Iteration #4-------n = 4----------s = 11

I just have trouble with this one because I don't know if n is updated within the iteration, or if n = 2 for iteration 1 and n = 3 for iteration 2.
Last edited on
1
2
double x = sqrt(2); double y = 2;
if (x * x == y)


floating points are approximations. x is not EXACTLY the square root of 2, it's just a very close approximation.

When you multiply x by itself, you're probably getting 1.999999999999999 or something to that effect, which does not equal 2, so that condition returns false.

Always be wary when using != and == to compare floating point numbers. In practice, you should probably never do it.

I just have trouble with this one because I don't know if n is updated within the iteration, or if n = 2 for iteration 1 and n = 3 for iteration 2.


No, n would be 1 for the entire loop, and would only be 2 once the loop completes. You are not incrementing n within the loop body. So the result would be:

Iteration 1: n=1, s=2
Iteration 2: n=1, s=3
Iteration 3: n=1, s=4
etc
Topic archived. No new replies allowed.