Board index » cppbuilder » Problem with calc's

Problem with calc's


2005-08-11 09:20:32 AM
cppbuilder2
Hello,
I have this code, for example...
DWORD result, count, size;
count = 42949693;
size = 103886722;
result = (count*100)/size; --->why result is 0, it must be
41,342812799502904711922665150605
Can someone help me...
Thanks in advance
Paulo Dias
 
 

Re:Problem with calc's

On Thu, 11 Aug 2005 02:20:32 +0100, Paulo Dias wrote:
Quote
Can someone help me...
What is the maximum size of DWORD?
--
liz
 

Re:Problem with calc's

sorry my newbie question
I already found a way to deal with this.
Paulo Dias
"Paulo Dias" < XXXX@XXXXX.COM >escreveu na mensagem
Quote
Hello,

I have this code, for example...

DWORD result, count, size;

count = 42949693;
size = 103886722;

result = (count*100)/size; --->why result is 0, it must be
41,342812799502904711922665150605

Can someone help me...

Thanks in advance

Paulo Dias





 

{smallsort}

Re:Problem with calc's

"Paulo Dias" < XXXX@XXXXX.COM >wrote in message
Quote
result = (count*100)/size;
why result is 0, it must be
41,342812799502904711922665150605
It is 0 because you are doing your arithmetic using 32-bit values that lose
precision during the calculations.
When count is greater than 42949672 (which is the case in your example),
(count*100) will produce a product that is too large to fit into a 32-bit
variable. The product ends up wrapping back around to 0 starts counting up
from there (in your example, the product ends up being 2004). When you
divide that wrapped product (2004) by your divisor (103886722), you are
generating a floating-point result that is less than 0 (approx.
0,0000192902419233133566385894821091766 in your example) which then has its
decimals trunctated off when assigned to a non-floating-point 32-bit
variable, ending up with final result of 0.
If you cast your count to a 64-bit floating-point value before multiplying
it, the product will be a 64-bit floating-point value that correctly
preserves the precision of the multiplication without any wrapping. In your
example, the product of multiplying a 64-bit floating-point value of
42949693.0 will be 4294969300.0, not 2004.0. Dividing 4294969300.0 by
103886722 will then producing a 64-bit floating-point value of
41.3428127995029, which will become 41 when truncated to a 32-bit
non-floating-value variable.
In other words, change this:
result = (count*100)/size;
To this instead:
result = (((double)count)*100)/size;
Or this:
double d = count;
result = (d*100)/size;
Which can then become this:
double d = count;
d *= 100;
d /= size;
result = d;
Gambit