我正在尝试编写一个使用递归来完成大学作业的程序,但老师不希望我使用循环来解决问题,但这是一个 jGRASP java 程序。 这是作业:
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 循环)
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);
}
}
() 它有效,但代码没有检索到我正在寻找的答案,代码说当我寻找数字的平方根时,我得到了 625。
有谁知道如何解决或更改最后一个方法,以便我可以获得 jGRASP java 程序的数字的平方根?
是的。您可以使用牛顿法。
考虑是否要找到 sqrt(10)。那么方程 当 f(x) == 0 时,f(x) = x2 - 10 将求解 x。
f(x)的一阶导数是f'(x) = 2*x。因此,请阅读 wiki 页面,按照描述应用 x、f(x) 和 f'(x)。