顺序是:sum = 1 + 1/2 + 1/4 + 1/9 + 1/16 + 1/25+...
当我输入"2“时,它给出的和是1.25。当输入"2“时,它是如何加1+ 1/2的呢?
哦,我正在上一门入门级的java课程,所以我们还不能使用数组或任何更高级的东西。
提前感谢!
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
sum += 1.0 / (counter*counter);
}
System.out.println("The sum is: " + sum);
}
}发布于 2016-10-27 07:53:47
下面的代码将解决您的问题,我已经使用Math.pow()使序列运行,而不是将其两次相乘。
public static void main(String[] args) throws UnknownHostException {
//declarations
Scanner scan = new Scanner(System.in);
//to generate this sequence we take the first two as constants and start generating from the third onwards
double first = 1;//first number in the sequence
double second = 0.5;//second number in the sequence
double sum = first+second;//adding first and second
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1){
System.out.println("The sum is: " + first);
return;
}
if(n==2){
System.out.println("The sum is: " + sum);
return;
}
//process
for(int counter = 2; counter <n; counter += 1)
{
sum += 1.0 / Math.pow(counter, 2);//will be computed when you enter values when n is more than 3
}
System.out.println("The sum is: " + sum);
}发布于 2016-10-27 08:18:39
如果这就是你的序列,那么你真的应该从设置和等于1.5开始,然后剩下的部分就可以工作了。你的序列应该是一个几何序列,1/n^2,我认为这是一个错误。
public static void main(String[]args) {
Scanner scan = new Scanner(System.in);
double sum = 1.5;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
if(n==1)
System.out.println("The sum is: " + 1);
//process
for(int counter = 2; counter <n; counter++) {
double mul = counter*counter;
sum += 1.0/mul ;
}
System.out.println("The sum is: " + sum);
}输出:
Enter n:
2
The sum is: 1.5
Enter n:
3
The sum is: 1.75发布于 2016-10-27 08:23:52
您需要将"1“和"2”作为特殊情况进行管理。
import java.util.Scanner;
public class Sum
{
public static void main(String[] args)
{
//declarations
Scanner scan = new Scanner(System.in);
double sum = 0;
int n;
//input
System.out.println("Enter n: ");
n = scan.nextInt();
//process
for(int counter = 1; counter <= n; counter += 1)
{
if (counter == 1)
sum = 1;
else if (counter == 2 )
sum += 1.0/((counter-1)+(counter-1));
else
sum += 1.0 / ((counter-1)*(counter-1));
}
System.out.println("The sum is: " + sum);
}
}https://stackoverflow.com/questions/40273827
复制相似问题