Return To CS 110 Home

Colour Theme   Font Size Options
 
   
   
   
Rounding and Powers

Rounding and Power Functions


Video Summary: https://youtu.be/3tirBWDwTUo


In c++, there are three built in functions you can use to round. In order to use any of them, you will need to add "#include <cmath>" to the top of your program.

  1. round(num) will perform a standard round, where 4 and below goes down, 5 and above goes to the up
  2. ceil(num) will always round up
  3. floor(num) will always round down

To verify how these functions work, you could run the following demonstration:


You could also create your own rounding function using pow and truncation:

  1. The power function is pow(base, exponent)
  2. Truncation occurs when a number with decimals is converted to int. Whatever is leftover is simply removed and will have no influence on the resulting number

For this exercise, you will create your own rounding feature that will work at different levels of scale. You would need to:

  1. Multiply the number being rounded by 10 to the power of the (scale + 1).
  2. Add 5 to the result
  3. Divide by 10. To force truncation, you may need to use type casting
  4. Divide by 10 to the power of the level of scale (you already divided by 10 once, so you don't need +1)

A sample output might look like this:

Enter a number
3.14159
Enter the scale
4
The rounded number is: 3.1416
					

Solution