[sclug] Yet another c++ question

Tim Sutton tim at linfiniti.com
Sat Oct 25 09:05:38 UTC 2003


Hi

Many thanks Spencer. Makes a lot more sense now :-) And my problem is sorted 
now too!

Tim

On Sunday 11 May 2003 9:45 am, Spencer Collyer wrote:
> 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>

-- 
Get my public keys from:

http://tim.suttonfamily.co.uk/modules.php?name=Content&pa=showpage&pid=2




More information about the Sclug mailing list