1066 problem: the fall of 2004, Zhejiang Province Computer Rank Examination two C programming problem (2)

Title Description

Enter a positive number x and a positive integer value of n, the following formula is required. Requires the definition of two function calls: fact (n) calculated n factorial; mypow (x, n) n-th power of x (i.e., xn), two types of function return value is double.

      x - x2/2! + x3/3! + ... + (-1)n-1xn/n!

 

× outputs a 4 decimal places.

 

Entry

x n

Export

Sequence sum

Sample input
2.0 3
Sample Output
1.3333

import java.util.Scanner;

public class Main{
public static void main(String args[]){
  Scanner in = new Scanner(System.in);
  double x = in.nextDouble();
  int n = in.nextInt();
  double y=0.0;
  double sum=0.0;
  for(int i=1;i<=n;i++){
    y=Math.pow(-1, i-1)*mypow(x,i)/fact(i);
    sum+=y;
}
  System.out.printf("%.4f", sum);


}
  public static double fact(int n){
    double a=1;
    for(int i=1;i<=n;i++){
      a=a*i;
  }
    return a;
}
  public static double mypow(double x, int n){
  return Math.pow(x, n);
}
}

Guess you like

Origin www.cnblogs.com/xuesujun/p/11355598.html