Pages

Saturday, 20 August 2016

Chapter 6 Exercise 13, Introduction to Java Programming, Tenth Edition Y. Daniel LiangY.

*6.13 (Sum series) Write a method to compute the following series: m(i)=12+23+...+ii+1 Write a test program that displays the following table:

i m(i)
1 0.5000
2 1.1667
...
19 16.4023
20 17.3546



public class ProgrammingExercise6_13 {
 
 public static void main(String[] args) {
  System.out.printf("%-10s%-10s\n","i", "m(i)");
  System.out.println(String.format("%20s", "").replace(' ', '-'));
  for (int i = 1; i <= 20; i++) {
   System.out.printf("%-10d%-10.4f\n",i,sum(i));
  }
 
 }
  
 public static double sum(int n) {
  double sum=0;
  for (int i = 1; i <= n; i++) {
   sum+= 1.0*i/(i+1);
  }
  return sum; 
   
 }
 
}

No comments:

Post a Comment