初学者做习题
题目的命题以Xiti4q开头,后面的数字代表具体的题号
4.计算s=1+1/2+1/3+1/4+...+1/100的和。
//计算s=1+1/2+1/3—-----+1/100的和
public class Xiti4q4 {
public static void main(String[] args) {
double s = 0;
double i = 1;
do {
s = s + 1/i;
i = i + 1;
} while (i <= 100);
System.out.println("1+1/2+1/3.....+1/100=" + s);
}
}
------------------------------------------
##########################################
5.计算s=1-2/1+1/3-1/4+...-1/100的和。
//计算s=1-1/2+1/3-1/4+.....-1/100的和
public class Xiti4q5 {
/* 方法一:
public static void main(String[] args) {
double s=0;
double s1=0;
double s2=0;
double i = 1;
do {
s1 = s1 + 1/(2*i-1);
s2 = s2 + 1/(2*i);
i = i + 1;
} while (i <= 50);
s=s1-s2;
System.out.println("1+1/3+1/5...1/99=" + s1);
System.out.println("1+1/2+1/4.....+1/100=" + s2);
System.out.println("1+1/2+1/3.....+1/100=" + s);
} */
// 方法二:
private double s=0;
public void getsum(){
int j=1;
for (double i=1; i<=100 ; i++,j=-j)
s=s+j*(1/i);
System.out.println("1-1/2=1/3-1/4+....-1/100=" +s);
}
public static void main(String[] args)
{
Xiti4q5 xiti4q5=new Xiti4q5();
xiti4q5.getsum();
}
}
阅读(966) | 评论(0) | 转发(0) |