C++ decimal point and floats

911paramedic

Diamond Member
Jan 7, 2002
9,448
1
76
I was doing my homework and it asked "how will this value look when it is ouput?" and things along that line. So I answered them all but was wrong with all the floats. I answered the following with 3.0 and when I put it in my test program I get 3.

What gives? I thought floats, by their nature, had a decimal point and trailing zero. Is it being coerced into an int because of it being an absolute value?


#include <iostream>
#include <cstdlib>
#include <cmath>
#include <string>

using namespace std;

int main()
{

float x = sqrt(fabs(-4.0) + sqrt(25.0));

cout << endl;
cout << "x is :\t" << x << "\n" << endl;

system ("pause");
return 0;
}

(All the libraries are included because I write many problems with this same program, and I don't want to keep changing it. In a real program I know it's extra overhead, but this is only for testing.)

TIA
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
^ right, if you don't set an output precision the runtime library is free to pick it and you could get numbers like 5 and 5.0000001

If you want 5.0 or 5.00 you need to tell your code that.
 

911paramedic

Diamond Member
Jan 7, 2002
9,448
1
76
Nothing was said about setprecision, simply "what is the output of this?" And it asked for several absolute values of floats, derived from different equations.

My only question was about it dropping the decimal. Is it being coerced into an int?
 

DaveSimmons

Elite Member
Aug 12, 2001
40,730
670
126
My only question was about it dropping the decimal. Is it being coerced into an int?

No, 5 is a perfectly valid way for the runtime library to output a float value.

A float is stored internally as (signed digits) + (signed exponent) so 5 is stored as either (I forget which) binary values for 5 E+00 or 0.5 E+01.

"5.0 means a float" is really only true for the input to the compiler, where the .0 tells the compiler that it must not be an int. This is important for division (as in your earlier thread) and of course if you actually need a decimal value like 5.01.

But the output logic for the runtime library is (unless told otherwise) free to display the float 0.5 E+01 as any of 5, 5.0, 5.00, 5.0000, 5 E+00, etc.
 

911paramedic

Diamond Member
Jan 7, 2002
9,448
1
76
Thanks Dave, that answered my question. :)

I thought I was making a mistake somewhere or really didn't get something. (Not for lack of reading, that's for sure.)