Given a floating point number , convert it nearest integer.
Approach
Check if floating number is positive, add 0.5 to it otherwise subtract 0.5. For Example if input is -6.8 output will be -7 , if input is 7.5 output will be 8
Input: A floating point number.
using namespace std;
int round_float ( float r )
{
return ( r > 0.0 ) ? ( r + 0.5 ) : ( r - 0.5 );
}
int main()
{
float f;
cin>>f;
cout<<round_float ( f );
getchar();
}
Please comment if you find anything incorrect or have any other inputs
Approach
Check if floating number is positive, add 0.5 to it otherwise subtract 0.5. For Example if input is -6.8 output will be -7 , if input is 7.5 output will be 8
Input: A floating point number.
Output: Nearest integer
#include <iostream>
int round_float ( float r )
{
return ( r > 0.0 ) ? ( r + 0.5 ) : ( r - 0.5 );
}
int main()
{
float f;
cin>>f;
cout<<round_float ( f );
getchar();
}
Please comment if you find anything incorrect or have any other inputs
No comments:
Post a Comment