C++代码:
#include<iostream>
using namespace std;
double Fracts0(int index){//递归
if (index == 0)
return 0;
else
return 1.0 / index + Fracts0(index-1);//若改为--index,结果会出错
}
double Fracts1(int index){
double sum = 0;
for (int i = 1; i <= index; i++)
sum += 1.0 / (double)i;
return sum;
}
int main(){
cout << Fracts0(100) << endl;
cout << Fracts1(100) << endl;
system("pause");
return 0;
}
java代码:
package main;
public class test {
static double Fracts0(int index){//递归
if (index == 1)
return 1;
else
return 1.0 / (double)index + Fracts0(--index);//java比较智能
}
static double Fracts1(int index){
double sum = 0;
for (int i = 1; i <= index; i++)
sum += 1.0 / (double)i;
return sum;
}
public static void main(String[] args) {
System.out.println(Fracts0(100));
System.out.println(Fracts1(100));
}
}