|
From: Ioannis V. <no...@ya...> - 2001-10-31 03:25:46
|
> -----Original Message-----
> From: dev...@li...=20
> [mailto:dev...@li...] On Behalf=20
> Of Brian McCall
> Sent: Wednesday, October 31, 2001 4:20 AM
> To: dev...@li...
> Subject: [Dev-C++] Damn floats
>=20
>=20
> I'm having much trouble trying to manipulate floats. I try=20
> to truncate the=20
> part left of the decimal like so:
>=20
> float num1 =3D 45.34;
> int num2 =3D int (num1);
The first cast is not needed.
> num1 -=3D float (num2);
The second cast also is not needed. These are built in type conversions.
>=20
> But when I display num1 (cout<<num1), I get something like=20
> 0.3400001. What am I supposed to do about this?
num1 is a float. So you display it as a float. only if you cast it as an
int you will get an int.
But the style of casting you use is the worst. Type1(x) or (Type1)x
(C-style) are equivallent and the worst. Normally in your case you can
output the int part by using an int. however if you just play with these
things the most safe is:
#include <iostream>
int main()
{
using std::cout;
using std::endl;
=20
float f=3D0.2;
=20
cout<<static_cast<int>(f)<<endl;
}
However try to *never* use casting in C++ (in contrast with C).
> Actually, the reason I am doing this is as part of a function=20
> that assigns a=20
> float to a string, i.e., storing num1 in something like=20
> strNum1 as "45.34"=20
> (apstring strNum1; strNum1 =3D num1).
>=20
> Any ideas on either of these two problems?
If you wantt to create that function don't bother, you have got
sprintf().
char s[200];
sprintf(s, "%f", 4.4);
string sf=3Ds;
Ioannis
* Ioannis Vranos
* Programming pages: http://www.noicys.f2s.com
* Alternative URL: http://run.to/noicys
|