finding perfect cubes :)

Jan 6, 2014 at 1:59am
This snip of code will only find the perfect cubes 1, 8, and 27. when the user enters 100. It doesn't realize that 64 is a perfect cube. I can't find the problem. Any input would be much appreciated.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
 
#include <iostream>
#include <math.h>
using namespace std;
void display(int);

bool is_perfect_cube(int);

int main()
{
	int num;
	cout << "enter number\n";
	cin >> num;
	cout << "the cubes are\n\n";
	display(num);
	
}

bool is_perfect_cube(int N)
{
	if (pow((double)N, (double)1 / 3) == floor(pow((double)N, (double)1 / 3)))
		return true; 
	else return false;
}
void display(int num)
{
	for (int i = 1; i <= num; i++)
	{
			if (is_perfect_cube(i))
			{
				cout << i << endl;
			}
	}
}
Jan 6, 2014 at 2:07am
You ran into some floating-point inaccuracies.

pow((double)64, (double)1 / 3) is approximately 3.9999999999999996 for me, so the floor of that is 3, not 4 like you might expect.

I would consider sticking to integers instead, and instead of checking whether each number is a perfect cube, just calculate the perfect cubes until they exceed the inputted number. That way, you won't run into situations like this.
Last edited on Jan 6, 2014 at 2:09am
Topic archived. No new replies allowed.