有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

在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);
        }
    }
}

共 (2) 个答案

  1. # 1 楼答案

    您可以编写自己的round()方法,并使用它而不是在java类中构建:

    private static double round(double number, int places){
        double result;
        if(number == (int) number){
            return number;
        }
        result = (int) number;
        int multiplier = 1;
        for(int i = 0 ; i < places ; i++){
            multiplier*= 10;
        }
        double fraction = number - (int)number;
        result = result + ((int)(multiplier * fraction))*1.0/multiplier;
        return result;
    }
    
    public static void main(String[] args) {
        double d = 1.6546213;
        System.out.println(round(d, 2));
    }
    
  2. # 2 楼答案

    问题是,使用此算法时,最后的数字有一个错误元素,因此可以增加有效数字的数量,然后四舍五入到所需的数字:

    double myDouble = kb.nextDouble();
    {
        double testNum;
        double squareRoot = myInt/2;
        do
        {
            testNum=squareRoot;
            squareRoot = (testNum + (myInt/testNum))/2;
        }
        while(Math.abs(myDouble - (testNum * testNum)) > .00000001);//←decrease the error here
    
        //round squareRoot down to the num of decimals you want        
    
        System.out.println("\nThe square root of " + myDouble + " is " + squareRoot);
        }
    }