Re: C floating point
From: John Bode (john_bode_at_my-deja.com)
Date: 03/01/04
- Next message: Joona I Palaste: "Re: Elementary questions from a beginner"
- Previous message: Peter Pichler: "Re: Elementary questions from a beginner"
- In reply to: j0mbolar: "C floating point"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: 1 Mar 2004 13:41:33 -0800
j0mbolar@engineer.com (j0mbolar) wrote in message news:<2d31a9f9.0403010646.630174ed@posting.google.com>...
> C supports single precision floating point and double precision
> floating point but does it support fixed floating point? i've read
> that fixed floating point is more accurate than single precision
> floating point when dealing with dollars and cents.
C doesn't have a built-in fixed data type. What you can do is use an
integral type, scaled to the smallest unit. For example, the integer
12345 may represent $123.45 (counting in cents), or $12.345 (counting
in tenths of cents), or $1.2345 (counting in hundredths of cents).
As you can see, the more precise the unit, the smaller the range. An
unsigned 16-bit integer can count from 0 to 65,535; if you're counting
in hundredths of cents, that gives you a range of $0 to $6.5535.
Alternately, you can use a struct with two members, one to keep track
of whole dollar amounts, the other to keep track of fractional
amounts:
struct val {
int dollar;
int fract;
};
so that the value $12.3456 is stored as {12, 3456}. This way you can
represent a larger range of dollars, yet still keep the precision you
want; unfortunately, the arithmetic gets a little hairier. Think
about adding the values $12.3456 and $45.82; you'll have to perform
some kind of addition on the struct values {12, 3456} and {45, 8200}.
You could also represent values as arrays of int, where each array
element corresponds to a digit (i.e., the value 123456789 is
represented as int val[]={1,2,3,4,5,6,7,8,9};); this way you can
represent values with tens or hundreds of significant digits. Again,
the math operations aren't as straightforward as for built-in types.
- Next message: Joona I Palaste: "Re: Elementary questions from a beginner"
- Previous message: Peter Pichler: "Re: Elementary questions from a beginner"
- In reply to: j0mbolar: "C floating point"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|