0

I am doing the following

float years = (1/31536000) * 883102.00;

and I get years = 0000000

while the actual answer is 0.0.28

Any suggestion on what might be going wrong ?

Rajeshwar
  • 11,179
  • 26
  • 86
  • 158

7 Answers7

3

You should instead do

float years = (1.0/31536000.0) * 883102.00;

or

float years = (1.0/31536000) * 883102.00;

might work as well. Your very first number is treated as integer.

radarhead
  • 668
  • 3
  • 13
3

Just do

float years = 883102.00/31536000;

This will save computation. Since you are diving 1 by something and then multiplying. Alternatively just set 1 to 1.00

Quillion
  • 6,346
  • 11
  • 60
  • 97
1

1 is an int. The compiler then assumes that you are interested in working in ints and then 1/3153600 becomes 0. Just add a .0 to the 1 and your calc should work.

float years = (1.0/31536000) * 883102.00;
aepryus
  • 4,715
  • 5
  • 28
  • 41
1

That first term is being cast as an int, and thus is being rounded to 0. Try this:

float years = (1.00 / 31536000.00) * 883102.00
gr3co
  • 893
  • 1
  • 7
  • 15
  • 1
    Why only two zeroes after the decimal point? Shouldn’t you add a few more to be safe? – Eric Postpischil Aug 07 '13 at 16:36
  • There is no cast here. The first term has type `int` and the second term has type `int`, so their quotient has type `int`. The value is **truncated**, not rounded. – Pete Becker Aug 07 '13 at 16:36
  • @PeteBecker: “Rounding” is used to mean modification of a result to fit within a destination format (e.g., IEEE 754-2008 4.3), and various modes of rounding can be used, such as rounding toward zero. – Eric Postpischil Aug 07 '13 at 16:43
  • @EricPostpischil - the answer doesn't "rounds toward 0", it just says that the result is "rounded". That is, at best, sloppy terminology. The C++ language definition says that integer division truncates. (Formally, it discards the fractional part). – Pete Becker Aug 07 '13 at 16:49
1

(1/31536000) will yield 0 that multiplied by any number would be 0. Make atleast one of numerator or denominator float (like 1.0 or 31536000.0)

Anshul
  • 680
  • 1
  • 5
  • 19
1

883102.0 / 31536000 will do just what you want.

Pete Becker
  • 74,985
  • 8
  • 76
  • 165
1

Because of the Integer-Division

(1/31536000)

the fractional digits get truncate and the result is "zero". You have to add a dot:

(1.0/31536000.0) or (1./31536000.)
Zagatho
  • 523
  • 1
  • 6
  • 22