请教关于一道JAVA的编程题

来源:百度知道 编辑:UC知道 时间:2024/06/24 08:00:00
i>1 时
计算m(i)=1/2+2/3+.......+(i-1)/i

要求输出下表:
i m(i)
2 0.5
3 1.1667
.... ....
19 15.4523
20 16.4023

我写的程序 :

import javax.swing.JOptionPane;
public class Main {
public static void main(String[] args) {

String numString = JOptionPane.showInputDialog(null,
"Enter an index for the number:","Ex4.6",JOptionPane.QUESTION_MESSAGE);
double i=Double.parseDouble(numString);

if(i<=1)
JOptionPane.showMessageDialog(null,"the value you enter is wrong,the number must be bigger than 1 ",
"Ex4.6",JOptionPane.INFORMATION_MESSAGE);
else

JOptionPane.showMessageDialog(null,"the m(i) is "+factorial(i-1),
"Ex4.6",JOptionPane.INFORMATION_MESSAGE);
}
static double factorial(double i) {
double a = 1/2d+2/3d;
if(i==2)

帮你重新做了一个,你可以参考一下:

public class Test1 {
TreeMap<Integer,Double> map = new TreeMap<Integer,Double>();

static public void main(String[] sss) {
Test1 t = new Test1();
t.m(20);
// System.out.println(t.map);

for (int i = 2; i <= 20; i++) {
System.out.println(i + ":" + t.map.remove(t.map.firstKey()));
}

}

public double m (int i) {
double per = 0;
if (i == 2) {
map.put(2, 0.5);
return 1.0 / 2;
} else {
per = (i - 1.0) / i + m (i - 1);
map.put(i, per);
return per;
}
}
}

站个地,明早帮你改