在Java中使用循环而不是类来获取要舍入的数字
我试图得到一个数字的平方根,在该数字的0.000001范围内四舍五入。例如,10的sqrt=3.1622766。。。。。用双人床。我有,但四舍五入到3.162267是我的问题。我必须使用循环,不能使用类。谢谢你,杰瑞德
import java.util.Scanner;
public class squareRoot {
public static void main(String[] args) {
Scanner kb = new Scanner(System.in);
System.out.println("Please enter a non-negative integer.");
int myInt = kb.nextInt();
{
double testNum;
double squareRoot = myInt / 2;
do {
testNum = squareRoot;
squareRoot = (testNum + (myInt / testNum)) / 2;
}
while (squareRoot - (testNum * testNum) > .000001);
System.out.println("\nThe square root of " + myInt + " is " + squareRoot);
}
}
}
# 1 楼答案
您可以编写自己的
round()
方法,并使用它而不是在java类中构建:# 2 楼答案
问题是,使用此算法时,最后的数字有一个错误元素,因此可以增加有效数字的数量,然后四舍五入到所需的数字: