-1

I'm trying to run a loop that goes 1 + 1/3 + 1/5 - 1/7 + 1/9....so on

but it keeps coming up as 1!

I have tried

double answer = 1 + 1/3 + 1/5 - 1/7 + 1/9 - 1/11;
displays 1

the math is weird like I even messed around and tried

double answer = 1 / 5; //should display 0.2
displays 0!!!!!!!!
Average kid
  • 6,885
  • 6
  • 21
  • 17

5 Answers5

7

You are using integer math.

The result of an operation between two integers will be an integer, rounded towards 0.

So your code becomes:

double answer = 1 + 0 + 0 - 0 + 0 - 0;

Try this instead.

double answer = 1.0 + 1.0/3.0 + 1.0/5.0 - 1.0/7.0 + 1.0/9.0 - 1.0/11.0;
Drew Dormann
  • 59,987
  • 13
  • 123
  • 180
3

Because you are using integer literals. Try this:

double answer = 1 + 1/3.0 + 1/5.0 - 1/7.0 + 1/9.0 - 1/11.0;
2

In C++, when you divide one integer by another, you get an integer. Thus, 1/3 equals 0.

Try:

double answer = 1 + 1/3.0 + 1/5.0 - 1/7.0 + 1/9.0 - 1/11.0;
NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

The operation work on integer constants, then result is converted to double. You should define your constants as follows:

double answer = 1.0 + 1.0/3.0 + 1.0/5.0 - 1.0/7.0 + 1.0/9.0 - 1.0/11.0;
meyumer
  • 5,063
  • 1
  • 17
  • 21
2

Try 1.0/3.0, etc.

Otherwise, each sub-expression will evaluate to 0 as they are interpreted as integers.

Peter L.
  • 1,041
  • 2
  • 22
  • 26