Why my code doesn't work ?

Hi! I needed to write out all perfect cube numbers from interval. So I wrote the following code

1
2
3
4
5
6
7
for (int i=m;i<=n;i++) // the interval is from m to n
{ 
  if ( (cbrt(i)==(round(cbrt(i)))))
  {
   cout << i<<' ';}
  }
}


But the problem is that i don't get cubes which root can be devided by 3 ( like 27 (3^3); 216(6^3); 729 (9^3) e.c.)

I use Code::Blocks on Ubuntu.
Thanks for help!
Last edited on
Add some debug. What happens with this code?


1
2
3
4
5
6
7
8
for (int i=m;i<=n;i++)
{ 
  cout << std::setprecision(30) <<   "cbrt = " << cbrt(i) << "   rounded cbrt= " << round(cbrt(i)) << endl;  // #include <iomanip>  to get std::setprecision
  if ( (cbrt(i)==(round(cbrt(i)))))
  {
   cout << i<<' '; // I REMOVED A BAD CLOSING BRACE HERE
  }
}

You're comparing a double with itself, rounded, which is another double.

Time to learn about floating point and why floating point comparison is difficult; http://floating-point-gui.de/
Last edited on
Floating point values are imprecise so using == to compare them is not reliable. If I were doing this I would try to find a way that only involved calculations with integer.
I don't know what but something is wrong - I tried debug before and result was cbrt = 6 rounded cbrt =6 and still no output... same for other roots that can be divided by 3

p.s. Thanks for the article !
Last edited on
You didn't have enough precision in your output. Here's the result when i = 27:
cbrt = 3.00000000000000044408920985006   rounded cbrt= 3

Not the same.

Here's the result when i = 216:
cbrt = 6.00000000000000088817841970013   rounded cbrt= 6

Also not the same.

What's "wrong" is that, as you can clearly see, the two numbers being compared are not equal.
Last edited on
Ok thank you ! I will try to find better solution.
Topic archived. No new replies allowed.