I have an exercise that tell me these:
Functions
Problem 1
Function floor
may be used to round a number to a specific decimal place. The statement
y = floor( x * 10 + .5 ) / 10;
rounds x to the tenths position (the first position to the right of the decimal point). The statement
y = floor( x * 100 + .5 ) / 100;
rounds x to the hundredths position (the second position to the right of the decimal point).
Write a program that defines four functions to round a number x in various ways
a. roundToInteger( number )
b. roundToTenths( number )
c. roundToHundreths( number )
d. roundToThousandths( number )
For each value read, your program should print the original value, the number rounded to the nearest integer, the number rounded to the nearest tenth, the number rounded to the nearest hundredth, and the number rounded to the nearest thousandth.
Input Format
Input line contain a float number.
Output Format
Print the original value, the number rounded to the nearest integer, the number rounded
to the nearest tenth, the number rounded to the nearest hundredth, and the number
rounded to the nearest thousandth
Example:
Input
24567.8
Output
24567.8 24568 24570 24600
My solution (which is wrong) is:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double roundToInteger(double number)
{
double roundedNum;
roundedNum = floor(number + .5);
return roundedNum;
}
double roundToTenths(double number)
{
double roundedNum;
roundedNum = floor(number * 10.0 + .5) / 10.0;
return roundedNum;
}
double roundToHundreths(double number)
{
double roundedNum;
roundedNum = floor(number * 100.0 + .5) / 100.0;
return roundedNum;
}
double roundToThousandths(double number)
{
double roundedNum;
roundedNum = floor(number * 1000.0 + .5) / 1000.0;
return roundedNum;
}
int main()
{
double userInput = 0.0, userInput1 = 0.0, userInput2 = 0.0,userInput3 = 0.0, userInput4 = 0.0, originalVal = 0.0;
printf("Enter a double value: ");
scanf("%lf", &userInput);
originalVal = userInput;
userInput1 = roundToInteger(userInput);
userInput2 = roundToTenths(userInput);
userInput3 = roundToHundreths(userInput);
userInput4 = roundToThousandths(userInput);
printf("%lf %lf %lf %lf %lf", originalVal, userInput1,userInput2,userInput3, userInput4);
}
What in the formula I am doing wrong?
If the input is 24567.8
and the expected output is 24567.8 24568 24570 24600
, change your formulas from:
y = floor( x * 10...0 + .5 ) / 10...0;
To:
y = floor( x / 10...0 + .5 ) * 10...0;
In other words, you implemented correctly the formulas provided. Only thing wrong here is the fact the formulas are wrong for rounding powers of ten. Those are for rounding decimal places.