日期:2014-05-20  浏览次数:20745 次

java基础中的简单算法,在线等
java基础中的简单算法,在线等

要求:
1/1!+1/2!+1/3!+....

如何写代码呀,thanks

------解决方案--------------------
求极限?
------解决方案--------------------
public class JieCheng {

/**
* @param args
*/
// 1/1!+1/2!+1/3!+....

public static float sum(int i) {

float result = 1;

for (int j = i; i > 1; i--) {
result = result * i;
}

return 1 / result;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

int index = 3;

float sum = 0;

for (int i = 1; i <= index; i++) {
sum = sum + JieCheng.sum(i);
}
for (int i = 1; i <= index; i++) {
System.out.println(JieCheng.sum(i));
if(i<index){
System.out.println("+");
}

}
//System.out.println("-------------");
System.out.println("=");
System.out.println(sum);
}

}

------解决方案--------------------
Java code


private static double getResult(int n){
        double r=0.0;
        for(int i=1;i<=n;i++){
            r+=(1.0/(get(i)));
        }
        return r;
    }
    
    private static double get(int i){
        double r=1.0;
        for(int j=1;j<=i;j++){
            r*=j;
        }
        return r;
    }

------解决方案--------------------
public class JieCheng {

/**
* @param args
*/
// 1/1!+1/2!+1/3!+....

public static float sum(int i) {

float result = 1;

for (int j = i; i > 1; i--) {
result = result * i;
}

return 1 / result;
}

public static void main(String[] args) {
// TODO Auto-generated method stub

int index = 3;

float sum = 0;

for (int i = 1; i <= index; i++) {
sum = sum + JieCheng.sum(i);
}
for (int i = 1; i <= index; i++) {
System.out.println(JieCheng.sum(i));
if (i < index) {
System.out.println("+");
}

}
// System.out.println("-------------");
System.out.println("=");

System.out.println(sum);
System.out.println("-------------");
for (int i = 1; i <= index; i++) {
if (i < index) {
System.out.print("1/" + i + "! + ");
} else {
System.out.print("1/" + i + "! = " + sum);
}
}

}

}
------解决方案--------------------
用两个变量,比如一个sum用于保存和,另一个x用于保存阶乘
假设要求计算到n!的话,主要部分如下
sum=0;x=1;
for(int i=1;i<=n;i++){
x=1*x;
sum=sum+1/x;
}
------解决方案--------------------
阶乘的话考虑用BigInter或者重写乘法规则,不然很容易溢出。
------解决方案--------------------
探讨
阶乘的话考虑用BigInter或者重写乘法规则,不然很容易溢出。

------解决方案--------------------
public class Test
{
public static void main(String[] args)
{
new Test();
}

public Test()
{
double sum = 0;
for(int i = 1 ; i < 3 ; i++)
{
sum += 1.0/calFactorial(i);
}
System.out.println(sum);
}

public double calFactorial(int i)
{
if(i == 1)
{
return 1;
}
else
{
return calFactorial(i - 1) * i;