views:

102

answers:

2

Hi, I feel really silly asking this because I know how to do it 101 ways, but not the way it is defined in the book. (note, I know C++)

So far, we have only gone over the very basics of C++. So basically, we know variables, assignment, and basic casting.

In the book I am having trouble with this portion of the problem:

  • prompt the user to input a decimal number
  • Convert that number to the nearest integer and print it to the screen

So I have the trivial code:

double n;
cout<<"Number: ";
cin >> n;
cout <<endl<<static_cast<int>(n)<<endl;

But I realized this does not work for me. It will always truncate the decimal so that 1.9 -> 1 rather than the expected 1.9 -> 2

How do I fix this using only what I "know"? (as in, without round() or if statements and such)

Is this a standards compliance problem? At school I thought I had something similar working with Visual C++ 2005 on Windows XP 32 bit, but now I'm at my home trying to do the same thing and it's not working. My home compiler is gcc 3.3.5 on OpenBSD 64bit. Or could this be a typo in the book?

+9  A: 

static_cast<int>(n+0.5)

Or static_cast<int>(n >= 0 ? n + 0.5 : n - 0.5) for more proper behavior on negative n.

ephemient
ah dang it.. Noooow I remember my teacher saying that... wow I feel dumb.
Earlz
Just remember that it's undefined behaviour to cast a floating type to an integral type if the value of the source doesn't fit into the destination. So if the user inputs "1.0e10", anything can happen. If you're lucky, your compiler manual tells you what. `ceil` and `floor` functions exist for a reason ;-)
Steve Jessop
A: 

Just so you know, this is not a problem with your compiler. In C++, when you convert a float to an integral type, the value is always truncated.

John Dibling