bump....
bump....
Last edited by xbusterx; 09-21-2008 at 04:05 PM.
First you need to read the number with decimal places, so read in a float, not an int.
Then you can either just use std::setprecision to make the output operator do the rounding, or you can use a cast to int to cut away the decimal places. Since the latter always rounds down, though, you can add .5 first:
Code:float f1 = 3.2f; int i1 = static_cast<int>(f1 + 0.5f); // -> 3.7 -> 3 float f2 = 3.7f; int i2 = static_cast<int>(f2 + 0.5f); // -> 4.2 -> 4
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
If your going to manually round it, CornedBee's suggestion will only work for positive numbers,
but incase you need to do it with a negative value, you can use this simple function.
Hope this helps.Code:#define Abs(val) ((val) < 0 ? -(val) : (val)) int round(float f) { int abs_rounded = static_cast<int>( Abs(f) + 0.5f ); return (f < 0.0f ? -abs_rounded : abs_rounded); }
Ok here is the new one
float num;
cout<< "Please enter a positive value";
cin>> num=static_cast<int>(num + 0.5f);
cout<< num << endl;
What exactly do you expect this line to do?cin>> num=static_cast<int>(num + 0.5f);
All the buzzt!
CornedBee
"There is not now, nor has there ever been, nor will there ever be, any programming language in which it is the least bit difficult to write bad code."
- Flon's Law
There are a few problems with this line:
1)cin>> num evaluates to cin. This is so tht you can chain multiple >> together. But in this case that means you assign the value on the right to cin, not num.
2) you use num and change num in the same expression. Using a variable in this way is disallowed, except when the old variable is used to calculate it's new value, or when sequencing operators (&&, ||, ?:, and ,[comma]) seperate the two uses.
3)You also intended to change num twice in the same line. this is also disallowed, except again when sequencing operators are used.
As matsp said, break this expression into parts.
It is too clear and so it is hard to see.
A dunce once searched for fire with a lighted lantern.
Had he known what fire was,
He could have cooked his rice much sooner.