算是搞清楚了四舍五入的算法。
代码如下:
package example;
//JHTP Exercise 6.10: Rounding Numbers
//by pandenghuang@163.com
/**(Rounding Numbers) To round numbers to specific decimal places, use a statement like
y = Math.floor(x * 10 + 0.5) / 10;
which rounds x to the tenths position (i.e., the first position to the right of the decimal point), or
y = Math.floor(x * 100 + 0.5) / 100;
which rounds x to the hundredths position (i.e., the second position to the right of the decimal
point). Write an application that defines four methods for rounding a number x in various ways:
a) roundToInteger(number)
b) roundToTenths(number)
c) roundToHundredths(number)
d) roundToThousandths(number)
For each value read, your program should display 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.*/
import java.util.Scanner;
public class RoundingNumbers
{
public static double RoundNumber(double number,int precision){
double rounded=0.0;
if (precision==0)
rounded = Math.floor(number+0.5);
else
rounded = Math.floor(number * Math.pow(10, precision-1)*10 + 0.5) / (10*Math.pow(10, precision-1));
return rounded;
}
public static void main(String[] args)
{
double number=0.0;
int precision=1;
double rounded=0.0;
Scanner input=new Scanner(System.in);
do {
System.out.print("请输入要四舍五入的数字(输入-1退出):");
number=input.nextDouble();
if(number==-1)
System.out.print("已退出程序");
else
{
System.out.print("请输入要四舍五入的精度(整数请输入0,十分位请输入1,百分位2,依次类推):");
precision=input.nextInt();
rounded=RoundNumber (number,precision);
switch (precision){
case 3:
System.out.printf("原数为:%f,千分位四舍五入后为:%.3f\n",number,rounded);
case 2:
System.out.printf("原数为:%f,百分位四舍五入后为:%.2f\n",number,rounded);
case 1:
System.out.printf("原数为:%f,十分位四舍五入后为:%.1f\n",number,rounded);
case 0:
System.out.printf("原数为:%f,四舍五入取整后为:%.0f\n",number,rounded);
}
}
}
while (number!=-1);
}
}
运行结果:
请输入要四舍五入的数字(输入-1退出):3.115
请输入要四舍五入的精度(整数,十分位请输入1,百分位2,依次类推): 2
原数为:3.115000,百分位四舍五入后为:3.12
原数为:3.115000,十分位四舍五入后为:3.1
原数为:3.115000,四舍五入取整后为:3
请输入要四舍五入的数字(输入-1退出): 3.5
请输入要四舍五入的精度(整数,十分位请输入1,百分位2,依次类推):2
原数为:3.500000,百分位四舍五入后为:3.50
原数为:3.500000,十分位四舍五入后为:3.5
原数为:3.500000,四舍五入取整后为:4
请输入要四舍五入的数字(输入-1退出):4.5589
请输入要四舍五入的精度(整数,十分位请输入1,百分位2,依次类推):3
原数为:4.558900,千分位四舍五入后为:4.559
原数为:4.558900,百分位四舍五入后为:4.56
原数为:4.558900,十分位四舍五入后为:4.6
原数为:4.558900,四舍五入取整后为:5
请输入要四舍五入的数字(输入-1退出):4.3484
请输入要四舍五入的精度(整数,十分位请输入1,百分位2,依次类推):3
原数为:4.348400,千分位四舍五入后为:4.348
原数为:4.348400,百分位四舍五入后为:4.35
原数为:4.348400,十分位四舍五入后为:4.3
原数为:4.348400,四舍五入取整后为:4
请输入要四舍五入的数字(输入-1退出):-1
已退出程序