题目:18.4 (对数列求和)
编写一个递归方法来盘算下面的级数:
编写一个测试程序,为i = 1, 2, …, 10显示m(i)
编程练习题18_4SumOfSequences.java
- package chapter_18;
- public class 编程练习题18_4SumOfSequences {
- public static void main(String[] args) {
- for(int i = 1;i <= 10;i++) {//从1到10
- System.out.printf("When i is %d, the sum of the fraction is %.2f\n",i,sequences(i));
- }
- }
- public static double sequences(int n) {
- return sequences(1,n);
- }
-
- public static double sequences(int i,int n) {
- if(i > n)// 如果i大于n,说明已经超出了范围,返回0(因为没有元素可加)
- return 0;
- else return 1.0/i + sequences(i+1, n);// 否则,返回当前数的倒数加上从i+1到n的倒数之和
- }
- }
复制代码
- When i is 1, the sum of the fraction is 1.00
- When i is 2, the sum of the fraction is 1.50
- When i is 3, the sum of the fraction is 1.83
- When i is 4, the sum of the fraction is 2.08
- When i is 5, the sum of the fraction is 2.28
- When i is 6, the sum of the fraction is 2.45
- When i is 7, the sum of the fraction is 2.59
- When i is 8, the sum of the fraction is 2.72
- When i is 9, the sum of the fraction is 2.83
- When i is 10, the sum of the fraction is 2.93
复制代码
免责声明:如果侵犯了您的权益,请联系站长,我们会及时删除侵权内容,谢谢合作!更多信息从访问主页:qidao123.com:ToB企服之家,中国第一个企服评测及商务社交产业平台。 |