[sclug] Yet another c++ question

Spencer Collyer spencer at lasermount.uklinux.net
Sat Oct 25 09:05:38 UTC 2003


On Sun, 11 May 2003 00:23:11 +0100, Tim Sutton wrote:
> Ok this one confuses me:
> 
> cout << "Test : " << (10388820/108262440)*100 << endl;
> 
> Test : 0
> 
> Yet the same expression in gnumeric gives the more expected: 9.59

The problem is that the expression is being evaluated using integer
arithmetic. This is the way C++ (and C) do their arithmetic if there are
no floating point values involved. The division 10388820/108262440 in
integer maths gives you 0, and so the whole expression will return 0. 

As it looks like you want a floating point result, you need to force one
of the numbers to be floating point. If they are actual constants, just
make one of the numbers in the division sub-expression floating point
(e.g. 10388820/108262440.0 would work) and the whole expression will be
evaluated using fp maths.

Note: I don't think it would be enough to make the 100 floating point (as
100.0), as the division sub-expression would still be done using integer
maths before being promoted to a float.

In the more general case of two variables, you can cast one of them to
floating point. Say you have the expression a/b, where a and b are both
integer variables, you can force this to be evaluated using fp math by
saying static_cast<float>(a)/b or a/static_cast<float>(b). You could
replace 'float' with 'double' for more precision.

HTH 

S>

-- 
<<< Eagles may soar, but weasels don't get sucked into jet engines >>>
9:22am up 80 days, 11:02, 15 users, load average: 0.00, 0.29, 0.47
Registered Linux User #232457



More information about the Sclug mailing list