Java语言程序计划基础篇_编程练习题18.4 (对数列求和)

打印 上一主题 下一主题

主题 527|帖子 527|积分 1581

题目: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企服之家,中国第一个企服评测及商务社交产业平台。

本帖子中包含更多资源

您需要 登录 才可以下载或查看,没有账号?立即注册

x
回复

使用道具 举报

0 个回复

倒序浏览

快速回复

您需要登录后才可以回帖 登录 or 立即注册

本版积分规则

老婆出轨

金牌会员
这个人很懒什么都没写!

标签云

快速回复 返回顶部 返回列表