我有一个练习告诉我:
函数
问题1
函数floor
可用于将数字四舍五入到特定的小数点。声明
y = floor( x * 10 + .5 ) / 10;
将x四舍五入到十分位(小数点右侧的第一个位置(。这个报表
y = floor( x * 100 + .5 ) / 100;
将x舍入到第一百个位置(小数点右侧的第二个位置点(。
编写一个程序,定义四个函数,以各种方式对数字x进行四舍五入
a。roundToInteger(数字(
b。roundToTenths(数字(
c。roundToHundreths(数字(
d。roundToThousandths(数字(
对于读取的每个值,程序应打印原始值,数字四舍五入为最接近的整数,四舍五入到最接近的十分之一的数字,四舍五入到最接近的百分之一,以及四舍五入到最接近的千分之一的数字。
输入格式
输入行包含一个浮点数。
输出格式
打印原始值,数字四舍五入到最接近的整数,数字四入最接近的十分之一,四舍五入到最接近的百分之一,以及四舍五入到最近的千分之一
示例:
输入
24567.8
输出
245 67.8 24568 24570 24600
我的解决方案(这是错误的(是:
#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);
}
公式里我做错了什么?
如果输入是24567.8
,而预期输出是24567.8 24568 24570 24600
,则将公式从以下项更改:
y = floor( x * 10...0 + .5 ) / 10...0;
收件人:
y = floor( x / 10...0 + .5 ) * 10...0;
换句话说,您正确地实现了所提供的公式。这里唯一错误的是,公式对10的四舍五入是错误的。这些是小数点后四舍五入的。