我是一个刚刚进入循环的Java初学者。我试图写一个程序读入一个目标,并找到第一个n,例如1 + 1/2 + 1/3 + ... + 1/n>目标。该问题提供了一个代码,初始化n和总和缺失以及缺少while和它的语句的条件。如何在Java中达到指定目标时停止对谐波序列进行求和?
我能够找出如何制作谐波系列循环,但我不确定如何设置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);
}
}
答案就在问题:*开头n = 1 *不确定你的循环在每次迭代中递减n而不是增加它。 –
谢谢你的提示,我想我开始的方向是错的...... – Vickie