有没有一种方法可以在不使用Math.sqrt()且不使用循环的情况下制作sqrt函数?

问题描述 投票:0回答:1

我正在尝试编写一个使用递归来完成大学作业的程序,但老师不希望我使用循环来解决问题,但这是一个 jGRASP java 程序。 这是作业:homework attachment

My code

我尝试了这段代码:my code

import java.util.Scanner;

public class SquareRoot {
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   System.out.println("Enter a number: ");
   int x = scanner.nextInt();
   System.out.println("Enter a number: ");
   int y = scanner.nextInt();
   
   System.out.println("" + powS(x));
   System.out.println("" + powNS(y));
 }
 
 public static int powS(int x) {
   int result = (2 * x) - 1;
   if (x == 0) {
     return 0;
   }
   return result + powS(x-1);
 }
 
 public static int powNS(int y) {
   int solution = (2 * y) - 1;
   if (y == 0) {
     return 0;
   }
   return solution + powS(y-1);
 }
}

平方函数有效,但唯一的问题是我不知道如何更改最后一个方法来创建没有循环的平方根函数(没有 while 循环,没有 for 循环)

我尝试了这段代码:my code

import java.util.Scanner;

public class SquareRoot9 {
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   System.out.println("Enter a number: ");
   int x = scanner.nextInt();
   System.out.println("Enter a number: ");
   int y = scanner.nextInt();
   
   System.out.println("" + powS(x));
   System.out.println("" + powNS(y));
 }
 
 public static int powS(int x) {
   int result = 2 * (x-1);
   if (x == 0) {
     return 0;
   }
   return result * powS(x-1);
 }
 
 public static int powNS(int y) {
   int solution = 2 * (y-1);
   if (y == 0) {
     return 1;
   }
   if (y == 1) {
     return solution;
   }
   return solution / powNS(y-1);
 }
}

但是有一个错误

然后我尝试了这段代码:[我的代码]

import java.util.Scanner;

public class SquareRoot10 {
 public static void main(String[] args) {
   Scanner scanner = new Scanner(System.in);
   System.out.println("Enter a number: ");
   int x = scanner.nextInt();
   System.out.println("Enter a number: ");
   int y = scanner.nextInt();
   
   System.out.println("" + powS(x));
   System.out.println("" + powNS(y));
 }
 
 public static int powS(int x) {
   int result = (2 * x) - 1;
   if (x == 0) {
     return 0;
   }
   return result + powS(x-1);
 }
 
 public static int powNS(int y) {
   int solution = (2 / y) - 1;
   if (y == 0) {
     return 0;
   }
   return solution + powS(y-1);
 }
}

(https://i.stack.imgur.com/2ZRQV.png) 它有效,但代码没有检索到我正在寻找的答案,代码说当我寻找数字的平方根时,我得到了 625。

有谁知道如何解决或更改最后一个方法,以便我可以获得 jGRASP java 程序的数字的平方根?

java recursion jgrasp
1个回答
0
投票

是的。您可以使用牛顿法

考虑是否要找到 sqrt(10)。那么方程 当 f(x) == 0 时,f(x) = x2 - 10 将求解 x

f(x)的一阶导数是f'(x) = 2*x。因此,请阅读 wiki 页面,按照描述应用 x、f(x) 和 f'(x)

    首先循环执行以确保算法已完成。
  • 然后递归地执行以满足要求。
  • 在这两种情况下,当
  • |xn+1 - xn| 在合理的容差范围内时,您应该停止迭代。
  • 最后,您将需要使用一些变量代替上述方程中的
  • 10 来获取任何数字的平方根。
© www.soinside.com 2019 - 2024. All rights reserved.