ToB企服应用市场:ToB评测及商务社交产业平台

标题: Java语言程序计划基础篇_编程练习题18.4 (对数列求和) [打印本页]

作者: 老婆出轨    时间: 2024-9-9 13:50
标题: Java语言程序计划基础篇_编程练习题18.4 (对数列求和)
题目:18.4 (对数列求和)

编写一个递归方法来盘算下面的级数:

编写一个测试程序,为i = 1, 2, …, 10显示m(i)

   编程练习题18_4SumOfSequences.java 
  1. package chapter_18;
  2. public class 编程练习题18_4SumOfSequences {
  3.         public static void main(String[] args) {
  4.                 for(int i = 1;i <= 10;i++) {//从1到10
  5.                         System.out.printf("When i is %d, the sum of the fraction is %.2f\n",i,sequences(i));
  6.                 }
  7.         }
  8.         public static double sequences(int n) {
  9.                 return sequences(1,n);
  10.         }
  11.        
  12.         public static double sequences(int i,int n) {
  13.                 if(i > n)// 如果i大于n,说明已经超出了范围,返回0(因为没有元素可加)  
  14.                         return 0;
  15.                 else return 1.0/i + sequences(i+1, n);// 否则,返回当前数的倒数加上从i+1到n的倒数之和  
  16.         }
  17. }
复制代码

  1. When i is 1, the sum of the fraction is 1.00
  2. When i is 2, the sum of the fraction is 1.50
  3. When i is 3, the sum of the fraction is 1.83
  4. When i is 4, the sum of the fraction is 2.08
  5. When i is 5, the sum of the fraction is 2.28
  6. When i is 6, the sum of the fraction is 2.45
  7. When i is 7, the sum of the fraction is 2.59
  8. When i is 8, the sum of the fraction is 2.72
  9. When i is 9, the sum of the fraction is 2.83
  10. When i is 10, the sum of the fraction is 2.93
复制代码


免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。




欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/) Powered by Discuz! X3.4