This is the mail archive of the gcc-bugs@gcc.gnu.org mailing list for the GCC project.


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]

Floats different printing than doubles?


I wrote a simple cash register program (c++) that was supposed to print the
input number multiplied by 1.03 rounded to two decimal places.

I failed to get the correct output when the type was double, but it works
fine when the type is float. It seems to have difficulty with rounding .055
to .06, but it will round .056 to .06. Float works fine in all cases I
tested.

I am running gcc-2.95.2 on a sun sparc with solaris 2.5.1, no extra config
flags.
-------------------------------------------------------------
//    cash.cpp
#include <iostream>

int main()
{
        float val1;             // Input Value
        float res;              // Result

        cout << "\nCash Register Running\n";
        cout << "Please Input Value: ";
        cin >> val1;
        res = val1 * 1.03;
        cout.precision(2);
        cout.flags(ios::fixed | ios::showpoint);
        cout << "\nTotal Sale = " << res << "\n\n";
        cout << "Thank you. Have a nice day.\n" << endl;

        return 0;
}
-------------------------------------------------------------

compiled with:
$ c++ cash.cpp
run with:
$ a.out
input of 18.5 gives output of 19.06
change the float types to double and input of 18.5 gives output of 19.05

This I thought was wrong. :)

-- 
    -- Cd --                    Christopher Denney
-- 
The correct way to punctuate a sentence that starts: "Of course it is none
of my business, but --" is to place a period after the word "but." Don't use
excessive force in supplying such a moron with a period. Cutting his throat
is only a momentary pleasure and is bound to get you talked about.
-- Lazarus Long, "Time Enough for Love" -R.A. Heinlein


Index Nav: [Date Index] [Subject Index] [Author Index] [Thread Index]
Message Nav: [Date Prev] [Date Next] [Thread Prev] [Thread Next]