|
-
Jul 18th, 2003, 07:32 PM
#1
Thread Starter
Hyperactive Member
casting question! Is this roudning to the nearest integer?.:Resolved:.
Hello everyone!
I'm reading some exericses and it wants me to round the number to the nearest integer. Okay this is quite easy I thought, but does this mean if i have:
34.6 to print 34
or does it mean
34.6 to print 35?
my code does the first thing, it prints 34 not 35.
Code:
double x = 34.6;
cout <<"x: " << static_cast<int>(x) << endl;
this just truncates the decimal number and prints 34! is this right?
Thanks for listening,
Last edited by voidflux; Jul 20th, 2003 at 12:54 PM.
C¤ry Sanchez
Computer Science/Engineering
@ Penn State
IBM.zSeries Intern
Mandriva 2007
-
Jul 18th, 2003, 09:50 PM
#2
Hyperactive Member
Re: casting question! Is this roudning to the nearest integer?
Originally posted by voidflux
Hello everyone!
I'm reading some exericses and it wants me to round the number to the nearest integer. Okay this is quite easy I thought, but does this mean if i have:
34.6 to print 34
or does it mean
34.6 to print 35?
my code does the first thing, it prints 34 not 35.
Code:
double x = 34.6;
cout <<"x: " << static_cast<int>(x) << endl;
this just truncates the decimal number and prints 34! is this right?
Thanks for listening,
Nope, 34.6 rounded to the nearest integer is 35 (normally).
Last edited by Comreak; Jul 18th, 2003 at 09:55 PM.
-
Jul 19th, 2003, 05:00 AM
#3
Hyperactive Member
It usually truncate off the decimal point part.
There is no way round about this. You would have to use floor() and ceil() in <cmath> header.
-
Jul 19th, 2003, 06:09 PM
#4
Thread Starter
Hyperactive Member
Thanks guys! this book must have a typo then because this is only chapter 2 and they only introduced how to static_cast somthing, never how to use the cmath functions for rounding but thanks for the info!
C¤ry Sanchez
Computer Science/Engineering
@ Penn State
IBM.zSeries Intern
Mandriva 2007
-
Jul 20th, 2003, 12:53 PM
#5
Thread Starter
Hyperactive Member
I just found out that you can round numbers by just using some basic ostream objects, such as setprecision and fixed, yay!
C¤ry Sanchez
Computer Science/Engineering
@ Penn State
IBM.zSeries Intern
Mandriva 2007
-
Jul 20th, 2003, 02:06 PM
#6
you can also round to the nearest integer in amazing mathemagical ways!
Code:
int RoundedValue = static_cast<int>(dblValue + .5);
Since casting to an int will just truncate the decimal part.
Every passing hour brings the Solar System forty-three thousand miles closer to Globular Cluster M13 in Hercules -- and still there are some misfits who insist that there is no such thing as progress.
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|