我想使用基本循环求和,所以我使用了以下代码:
// sum of first n terms in the series, 1 - 1/1! + 2/2! - 3/3!...
package assignment02;
import java.util.Scanner;
public class P7Bnew {
public static void main(String[] args) {
Scanner in = new Scanner (System.in);
System.out.println("Enter number of terms.");
int n = in.nextInt();
// using for loop to find sum
double sum =1;
for (int i =1; i<n ; i++)
{
int fact = 1;
for (int j=1; j<=i; j++)
{
fact *= i;
}
if (i%2==0)
sum+= ((int)i/fact);
else
sum -= ((int)i/fact);
}
System.out.println("The sum of first "+n+ " terms is "+sum);
}
}
Run Code Online (Sandbox Code Playgroud)
我想限制使用预定义的函数。这样,对于 n>=4,我得到的总和为 1。所以我尝试了另一种方法来交替添加和减去项:
import java.util.*;
import java.lang.*;
import java.io.*;
class P7B
{
public static void main (String[] args) throws java.lang.Exception
{
Scanner in = new Scanner (System.in);
int a = in.nextInt();
double sum = 1;
for (int i=1; i<a ; i++)
{
int fact=1;
for (int j=2; j<=i;j++)
{
fact = fact * j;
}
int sign;
if ((i%2)==0)
sign =1;
else
sign = -1;
sum = (sum + (sign*(i/fact)));
}
System.out.println("The sum of the first "+a+ " terms of the series 1 - (1/1!) + (2/2!) - (3/3!)... is "+(sum)+".");
}
}
Run Code Online (Sandbox Code Playgroud)
但我得到了相同的结果。后来当我使用 Math.pow(-1, i) 而不是符号变量时,它给了我正确的结果。请告诉我为什么我最初的尝试给出的 n>=4 的总和不正确。
你的问题是, ini/fact以及(sign*i)/fact所有操作数 都是ints,因此你将得到 0 作为该计算的结果(1/2 等在整数数学中是 0 ,所以除了andi/i!之外,因为这只是和)。使用时你会得到一个,现在计算就可以了。1/1!2/2!1/12/2Math.pow(-1,i)double
因此,要修复您的代码,请使用强制转换double:
if (i%2==0)
sum += (double)i/fact;
else
sum -= (double)i/fact;
Run Code Online (Sandbox Code Playgroud)