ToB企服应用市场:ToB评测及商务社交产业平台
标题:
Java语言程序计划基础篇_编程练习题18.4 (对数列求和)
[打印本页]
作者:
老婆出轨
时间:
2024-9-9 13:50
标题:
Java语言程序计划基础篇_编程练习题18.4 (对数列求和)
题目: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企服之家,中国第一个企服评测及商务社交产业平台。
欢迎光临 ToB企服应用市场:ToB评测及商务社交产业平台 (https://dis.qidao123.com/)
Powered by Discuz! X3.4