3
double num1=3.3;
double num2=3.8;

//print output and round off
cout<<floor(num1+0.5)<<endl;
cout<<floor(num2+0.5)<<endl;

My task is to round the number first and then cast it to integer: the output of num1 and num2 after round off should be respectively 3.000000 and 4.000000. How should I cast it to int to get the aboved mentioned answers 3 and 4?

rocambille
  • 15,398
  • 12
  • 50
  • 68
Sylar
  • 45
  • 7
  • You can also use [`std::round`](http://en.cppreference.com/w/cpp/numeric/math/round) in C++11 or later. – vsoftco Oct 11 '16 at 12:42

2 Answers2

3

You can declare an int variable and assign the result of the floor, then output that int. The floor is no longer needed either, as the assigning to an int does that implicitly.

int i1 = num1+0.5;
cout<<i1<<endl;

Note that in your current code, floor() does not actually help in any way, as you are discarding the result. floor is not modifying its parameter, but returning its result, and you are not assigning it to anything. You could have used, for example,
num1 = floor(num1+0.5);
and then num1 would contain the result.

Aganju
  • 6,295
  • 1
  • 12
  • 23
  • Previously I've done the same thing as what you did, but my lecturer told me, by directly apply casting it will lead to truncation error, therefore she ask me to round off first and then cast it to int – Sylar Oct 11 '16 at 12:05
2

cout<<floor(num1+0.5)<<endl; will print 3.0. You don't need more cast here, but if you want to do it, use static_cast:

double num1=3.3;
double num2=3.8;

// to round off
int num1_as_int = static_cast<int>(floor(num1+0.5));
int num2_as_int = static_cast<int>(floor(num2+0.5));

//print output
cout<<num1_as_int<<endl;
cout<<num2_as_int<<endl;

More about static_cast here, and why you should use it instead of C-style casts here.

rocambille
  • 15,398
  • 12
  • 50
  • 68
  • ya, thanks for pointing out the error, I've re modified the question. but by doing static_cast, it means apply direct casting right? my lecturer wants me to round off then only cast it to int because she told me by applying direct casting will lead to truncation error – Sylar Oct 11 '16 at 12:06
  • She is right for negative values. E.g. `-2.6` should be rounded to `-3`: `-2.6+0.5` will be `-2.1` and `static_cast(-2.1)` will be `-2`, a truncation, while `floor(-2.1)` will be `-3.0` (and `static_cast(floor(-2.1))` will be `-3`). I edit my answer – rocambille Oct 11 '16 at 12:09