我正在尝试解决这个程序,打印其总和:(a/1)+(a/2)+(a/3)+(a/4)+........ ..+(a/n) 其中 a 由用户输入,n 的限制也由用户输入,这是我尝试的程序:
/**
* Program to
*
* Anirudh Gupta
* th August 2014
*/
import java.io.*;
public class Program87b
{
public static void main () throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
System.out.println("Enter the value of the numerator");
double a=Double.parseDouble(br.readLine());
System.out.println("Enter the limit for the denominator");
int limit=Integer.parseInt(br.readLine());
double n=1.0;
double sum=0.0;
while(n<=limit)
{
sum=+(a/n);
n++;
}
System.out.println(sum);
}
}
但是当我输入 a=4 和 n=5 时,我得到 0.8,这只是 (4/5) 的 ans,而不是 (4/1)+(4/2)+(4/3) 的总和+(4/4)+(4/5) 应该是 9.1333333333...
最佳答案
将 =+ 更改为 +=,我不确定变量“d”来自哪里,但我认为应该将其替换为“n”
public static void main () throws IOException
{
InputStreamReader isr=new InputStreamReader(System.in);
BufferedReader br= new BufferedReader(isr);
System.out.println("Enter the value of the numerator");
double a=Double.parseDouble(br.readLine());
System.out.println("Enter the limit for the denominator");
int limit=Integer.parseInt(br.readLine());
double n=1.0;
double sum=0.0;
while(n<=limit)
{
sum+=(a/n);
n++;
}
System.out.println(sum);
}
关于java - 编写一个程序,计算 (a/1)+(a/2)+(a/3)+(a/4)+........+(a/n) 之和,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27957273/