Question: Objective: Create a function that rounds a double number to the nearest integer. NOTE: You will receive NO credit for using the round functions that

Objective: Create a function that rounds a double number to the nearest integer.

  • NOTE: You will receive NO credit for using the round functions that are available in the math library. You have to create your own function.

Description:

Create a function that takes a double variable as its input and returns an integer variable as the output. The output will be rounded up if the decimal value is at 0.5 or greater.

  • Function Input: One double variable
  • Function Output: One integer variable

In your main() function read in a double value from the user. Call the function you created and output the integer that it returns.

Calculating Rounded Number:

Use the following procedure within your function to determine what number to return.

  1. Typecast the double input to an int variable. This will always be rounded down.
    • Example: input = 3.5, rounded down = 3
  2. Calculate the different between the input and the rounded down int variable. This will be the decimal point value by itself.
    • Example: Decimal = input - rounded down -> 3.5 - 3 -> 0.5
  3. If the decimal value is greater than or equal to 0.5, return the rounded down variable + 1
    • Example: 0.5 >= 0.5 so return 3+1
  4. Else return the rounded down variable as it is
    • Example: else return 3

Tips:

  • Use breakpoints and printf to test each of your calculations.
  • Don't be afraid to create extra variables within your function. It is better to have more variables and solve the problem than try for efficiency and get it wrong.
  • Pay attention to your data types.
    • We intentionally use an int variable at times to purposefully round down. At other steps a double is required as you need the decimal information.
    • When using printf and scanf remember that %i or %d is used for int variables and %lf is used for decimal.
  • This is similar to the "Largest" example from the problem solving section, except with different input and a slightly more complex evaluation within the function. That example can provide a good jumping off point for setting up a function and calling it from the main function.

Example Screenshots:

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!