8

Here is what I mean trying to do

 double x=1.1402
 double pow=1/3;
 std::pow(x,pow) -1;

result is 0 but I expect 0.4465

the equation is (1 + x) ^3= 1.1402, find x.

vehomzzz
  • 42,832
  • 72
  • 186
  • 216
  • 3
    Debugging tip: it would be obvious that nothing is wrong with pow() if you simply inspect the arguments being passed to pow(). You would see that the value of the second argument was zero instead of 1/3, showing that pow() is operating correctly and the problem lies in your code. – nobody Oct 16 '09 at 21:13
  • 1
    Ok I already solved it.. stupid ints – vehomzzz Oct 16 '09 at 21:13
  • 7
    EVERYBODY has made this mistake. – mob Oct 16 '09 at 21:18
  • Possible duplicate of [Dividing 1/n always returns 0.0](https://stackoverflow.com/questions/13331054/dividing-1-n-always-returns-0-0) – phuclv Mar 11 '19 at 14:54

4 Answers4

23

1/3 is 0. That's integer division.

Try:

double pow = 1.0 / 3.0;

For:

#include <iostream>
#include <cmath>

int main(void)
{
 double x = 1.1402;
 double pow = 1.0/3.0;
 std::cout << std::pow(x, pow) - 1;

}
GManNickG
  • 494,350
  • 52
  • 494
  • 543
  • Sometimes the simplest answer wins, sometimes the most complete. StackOverflow is randomizing the order of answers too, so sometimes whatever comes up on top wins. Luck of the draw. – Mark Ransom Oct 19 '09 at 21:09
  • It was more that he had already accepted my answer, and later changed it to that one. I don't hold any grudges, 13 votes is quite enough, though at the time I was maxed and the acception was my only method of getting rep. No problems though :) – GManNickG Oct 19 '09 at 21:15
13

1/3 is done as integer arithmetic, so you're assigning 0 to pow. Try pow(x, 1.0/3.0);

Jerry Coffin
  • 476,176
  • 80
  • 629
  • 1,111
9

Many have stated that 1/3 = 0, but have not explained why this is so.

C and C++ will perform the operation based on the the types of the operands. Since both operands are integers, it performs an integer division creating an integer result. When it is forced to assign that integer result to a double variable, it converts the integer 0 to a double 0.0.

It is not necessary to make both operands double, if either one is double the compiler will convert the other to double as well before performing the operation. 1.0/3 or 1/3.0 will both return the result you expected, as will 1.0/3.0.

Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
1

your 1/3 is integer division, the result of the integer division is 0.

Doug T.
  • 64,223
  • 27
  • 138
  • 202