我是Java的一个完全初学者,刚刚介绍了循环。我试着写一个读入目标的程序并找到第一个n,使得1 + 1/2 + 1/3 + ... + 1 / n>目标。该问题提供了一个代码,其初始化为n和sum,以及while及其语句缺失的情况。
我能够弄清楚如何制作谐波系列循环,但我不知道在超过目标时如何设置n来停止循环。我们还没学会关于类中的数组..
import java.util.Scanner;
/**
This program computes how many steps the sum 1 + 1/2 + 1/3 + ...
needs to exceed a given target.
*/
public class ReciprocalSum
{
public static void main(String[] args)
{
double sum = 0;
int n = ???? ;
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble();
int i = 0;
//Notes
// 1 + 1/2 + 1/3 + 1/4 + ..... 1/n
//Make a loop that repeats itself starting with n = 1 --> 1/1 + 1/2 + 1/3 + 1/4 + 1/n
// 1.0/n + (1.0/ n - 1) + (1.0/n-2) +.... if n =4 --> 1/4 + 1/3 + 1/2 + 1/1 as long as n >0
while ( n > 0)
{
sum += 1.0/n ;
n--;
}
System.out.println("n: " + n);
System.out.println("sum: " + sum);
}
}
答案 0 :(得分:2)
n
应该在循环中递增(因此它应该从0
开始),当你到达目标时应该退出循环:
int n = 0;
...
while (sum <= target)
{
n++;
sum += 1.0/n;
}
答案 1 :(得分:2)
因为Java 8+具有lambda,并且您可以生成范围1
到n
并执行计算并一步获得总和。基本上,你可以做到
Scanner in = new Scanner(System.in);
System.out.print("Target: ");
double target = in.nextDouble(), sum = 1.0;
int n = 1;
while (sum < target) {
sum = IntStream.range(1, n).mapToDouble(i -> 1.0 / i).sum();
n++;
}
System.out.printf("n=%d, sum=%.2f%n", n, sum);
答案 2 :(得分:1)
你可以通过计算系列的Exception in thread "main" java.lang.NoClassDefFoundError: org/apache/spark/mllib/recommendation/Rating
at java.lang.Class.getDeclaredMethods0(Native Method)
at java.lang.Class.privateGetDeclaredMethods(Class.java:2625)
at java.lang.Class.getMethod0(Class.java:2866)
at java.lang.Class.getMethod(Class.java:1676)
at com.intellij.rt.execution.application.AppMain.main(AppMain.java:126)
Caused by: java.lang.ClassNotFoundException: org.apache.spark.mllib.recommendation.Rating
at java.net.URLClassLoader$1.run(URLClassLoader.java:359)
at java.net.URLClassLoader$1.run(URLClassLoader.java:348)
at java.security.AccessController.doPrivileged(Native Method)
at java.net.URLClassLoader.findClass(URLClassLoader.java:347)
at java.lang.ClassLoader.loadClass(ClassLoader.java:425)
at sun.misc.Launcher$AppClassLoader.loadClass(Launcher.java:312)
at java.lang.ClassLoader.loadClass(ClassLoader.java:358)
... 5 more
Process finished with exit code 1
来实现这一点,直到它的总和大于目标值:
sum