-4

I think the title says everything. I want to define a variable i as the fraction 1/12. However, i is 0.

double i = 1/12;
std::cout << i; // Output: 0

Or, more specific, I want to calculate a power of something:

im_ = std::pow((1 + i), (1/12)) - 1;

However, the compile evaluates (1/12) as 0 and thus the result is wrong.

Steve
  • 361
  • 1
  • 2
  • 6

1 Answers1

1

Simple because 1/12 is evaluated as integer math, not floating point math.

1/12 becomes 0 because integer math does not take into account the decimal fractions.

To get the expected result you will need to write down the numbers as a floating point literal, like this: 1.0/12.0.

More details can be found here: Why can't I return a double from two ints being divided

Rolf ツ
  • 8,611
  • 6
  • 47
  • 72
  • That confuses me. I can define a double as decimal fraction such as 0.5. Then the output will be 0.5, as supposed. – Steve Dec 15 '17 at 13:02
  • @Steve: If you divide 2 integers, the compiler does an integer division, which always gives an int result. To get a double, supply a division with at least one double in it, and the compiler will perform a floating point division. – Michaël Roy Dec 15 '17 at 13:13