-4

I need to write a program in C++ which prints all of the numbers between -50 and 0 that satisfy the equation: 18^3-18x^2+6=0

My if statement doesn't seem to return any results, it should :(

I think I'm along the right lines....

for (int x = -50; x < 0; x++) {
    int y = pow(x, 3) - 18 * pow(x,3) + 6;
    if(y == 0)
        cout << y << endl;
}

Any help would be appreciated.

reto
  • 9,995
  • 5
  • 53
  • 52
  • 3
    Run it through a debugger. –  Nov 05 '14 at 10:35
  • What result should it return? (Also, your expression has 18x ^ **2**, but your code has 18 * pow(x, **3**) -- not the same). – David Schwartz Nov 05 '14 at 10:38
  • In your code you have `y = x³ - 18x³ + 6 = -17x³ + 6`. The roots of this polynominal are the third roots of `6/17`, none of which is integral. – Lumen Nov 05 '14 at 10:39

4 Answers4

3

Your equation doesn't have any integer roots.

It simplifies to: 3*(x+1)*(x-1)*x = -1. The integers dividing -1 are 1 and -1, so there is no integer solution to your equation.

fjardon
  • 7,921
  • 22
  • 31
0

Three errors:

  1. If you want to include 0, use x<=0 instead of x<0

  2. your function was wrong, pow(x,2) instead of pow(x,3)

  3. you should output x not y, otherwise you'll only output zero

    for(int x=-50;x<=0;x++){
        int y=pow(x,3)-18*pow(x,2)+6;
        if(y==0)
          cout << x << endl;
    }
    
Wajeb
  • 83
  • 7
0

You should use the double type for your variable y because the equation has no integer roots. However never check a double variable equal zero. This may help you.

Community
  • 1
  • 1
code monkey
  • 2,094
  • 3
  • 23
  • 26
  • Surely an integer type would be a better choice to represent an integer? – Mike Seymour Nov 05 '14 at 10:47
  • To calculate the result you need double because the equation has no integer roots. After that the result could be casted to integer if this is explicit wanted. – code monkey Nov 05 '14 at 10:50
  • 1
    The fact that the equation has no integer roots means there's no integer value of `x` for which `y==0`. I.e. you would need to make `x` double too. And then the next problem is that neither `x++` nor `x=x+1.0` works to find that root. – MSalters Nov 05 '14 at 16:17
  • @MSalters Yes you are right. I have overlooked that. – code monkey Nov 06 '14 at 07:01
0

Your equation in question and in code are different:

I think it should be this

for (int x = -50; x < 0; x++) {
   int y = pow(x, 3) - 18 * pow(x,2) + 6;
   if(y == 0)
       cout << y << endl; 

}

And also check if equation provided is correct or not

rishiAgar
  • 168
  • 3
  • 10