Sylar
Sylar

Reputation: 45

Rounding off and recast it as integer

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?

Upvotes: 3

Views: 118

Answers (2)

rocambille
rocambille

Reputation: 15976

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.

Upvotes: 2

Aganju
Aganju

Reputation: 6395

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.

Upvotes: 3

Related Questions