求2/1+3/2+5/3+8/5+13/8=?
public class HelloWorld {
public static void main(String[] args) {
double sum = 0.0;
double fz = 2.0;
double fm = 1.0;
for(int i = 0; i <= 5; i ++){
sum += (fz / fm);
fm = fz;
fz += fm;
}
System.out.println("sum:"+sum);
}
}
double sum = 0.0; double fz = 2.0; double fm = 1.0; double t = 0.0; for(int i = 0; i <= 4; i ++){ sum += (fz / fm); t=fm; fm = fz; fz += t; } System.out.println("sum:"+sum);
public class HelloWorld {
两个值交换,需要用一个中间值进行转化一下。
public static void main(String[] args) {
double sum = 0.0;
double fz = 2.0;
double fm = 1.0;
double t=0.0;
for (int i = 0; i <5; i++) {
sum += (fz / fm);
t=fz;
fz += fm;
fm = t;
}
System.out.println("sum:" + sum);
}
i=0时 fz = 2.0 fm = 1.0 sum = 2.0 当i = 1时, fm = fz = 2 fz+=fm(fz = fz+ fm = 2+2=4) 此时sum = 2.0 按你代码以此类推 当然不一样