CS21 Week3 In-Class Exercises

  1. When a floating point number is converted to an integer in C, the floating point value is truncated by throwing away 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 floating point value to the nearest integer.

    For a positive floating 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 portion of x is less than 0.5, the truncated value will be an integer less than x. If the decimal portion of x is 0.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 then truncating.

    Write a function Round(x) that rounds a floating point number x to the nearest integer. Demonstrate that your function works by designing a suitable main program to test it. Your program should conduct a thorough test over many possible values.

    Demonstrate your program for me when you are done.