#### Archived

This topic is now archived and is closed to further replies.

# My wierd problem

This topic is 5640 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

## Recommended Posts

I am creating a trendy little baseball sim, and everything is going cool, except I have a problem when I cast ints to doubles. I am trying to calculate avg with this:

double Average = (double)Hits / (double)AtBats;


Hits and AtBats are both integers, and of course average is a double. Now, as far as I can see, this should be ok, but when I use printf to print the figure in Average, the printed figure is sometimes the correct figure, and sometimes not. If i run a loop, around half of the figures are right, and half are out by a few percentage points. Anyone have any idea why this is? Pretty sure its not my code, because it is very basic.

##### Share on other sites
...???

So if you have 5 Hits and 10 AtBats it will only print "0.5" half of the time? What else does it print? If it''s something like "0.499999999999999" or "0.50000000000001" then it''s a standard "feature" of floating-point numbers : computers make approximation errors constantly when working with them.

ToohrVyk

##### Share on other sites
quote:
Original post by ToohrVyk
If it''s something like "0.499999999999999" or "0.50000000000001" then it''s a standard "feature" of floating-point numbers : computers make approximation errors constantly when working with them.

Yep. I''m not familiar with the scoring system in baseball, but if the figure will eventually be expressed as a percentage, then I''d recommend:

(a) using floats rather than doubles
(b) multiplying Hits by 100 before dividing it

Heck, if you do the second of those, you could probably avoid using floating-point numbers altogether.

Superpig
- saving pigs from untimely fates, and when he''s not doing that, runs The Binary Refinery.

1. 1
2. 2
3. 3
Rutin
22
4. 4
5. 5
khawk
14

• 9
• 11
• 11
• 23
• 12
• ### Forum Statistics

• Total Topics
633654
• Total Posts
3013169
×