When a ?oating-point number is converted to an integer in C++, the value is trun
ID: 3628918 • Letter: W
Question
When a ?oating-point number is converted to an integer in C++, the value is truncated by throwingaway any fraction. Thus, when 4.99999 is converted to an integer, the result is 4. In many cases,
it would be useful to have the option of rounding a ?oating-point value to the nearest integer. For a
positive ?oating-point number x, the rounding operation can be achieved by adding 0.5 to x and then
truncating the result to an integer. If the decimal fraction of x is less than .5, the truncated value will be
the integer less than x; if the fraction is .5 or more, the truncated value will be the next larger integer.
Because truncation always moves toward zero, negative numbers must be rounded by subtracting 0.5
and truncating, instead of adding 0.5.
Write a function Round(x) that rounds a ?oating-point number x to the nearest integer. Show that
your function works by writing a suitable main program to test it.
Explanation / Answer
#include<iostream>
using namespace std;
int Round(float x)
{
if(x>0) return (x+0.5);
if(x<0) return (x-0.5);
else return 0;
}
int main()
{
cout << Round(4.999999) << " " << endl;
cout << Round(-1.2) << " " << endl;
return 0;
}
Related Questions
Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.