public class Nitin12assignA6 {
public static void main(String args[]) throws IOException {
series ob = new series();
ob.input();
ob.findSum();
ob.display();
}
}
class series {
int x, n;
double sum;
series() {
x = n = 0;
sum = 0.0f;
}
void input() throws IOException {
BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
System.out.print("\nEnter the value of x = ");
x = Integer.parseInt(in.readLine());
System.out.print("Enter the value of n = ");
n = Integer.parseInt(in.readLine());
}
void display() {
System.out.println("The sum of Series upto " + n + " terms is: " + sum);
System.out.println();
}
long fact(int num) {
if(num == 1) {
return 1;
}
return num * fact(num - 1);
}
int power(int num, int exp) {
if(exp == 1) {
return 1;
}
return num * power(num, exp - 1);
}
double term(int numr, long denom) {
return(numr / denom);
}
void findSum() {
int u = 2, l = 4;
sum = 1.0f;
for(int i = 0; i < n; i++) {
if(l % 8 == 0) {
sum += term(power(x, u), fact(l));
// Test start
System.out.println("add" + sum + " power " + power(x, u) + " fact " + fact(l) + " x " + x + " u " + u
+ " l " + l);
System.out.println("term " + term(power(x, u), fact(l)));
System.out.println("test term " + term(5, 2)); // printing 2.0
// instead of 2.5
// Test end
} else {
sum -= term(power(x, u), fact(l));
// Test start
System.out.println("minus" + sum + " power " + power(x, u) + " fact " + fact(l) + " x " + x + " u " + u
+ " l " + l);
System.out.println("term " + term(power(x, u), fact(l)));
// Test end
}
u += 2;
l += 4;
}
}
}
//double term(int numr,long denom) //{return (numr/denom);} 这个函数没有返回双精度值。请帮助... 这个程序是找到一个系列最多 n 项的总和。示例 - 测试项返回 2.0 而不是 2.5...谢谢。