日期:2014-05-20 浏览次数:20715 次
public class TestCode { public static double getSun(double in) { double sun = 0; for (double i = 2; i <= in; i += 2) { sun = sun + 1 / i; } return sun; } public static void main(String[] args) { System.out.println(getSun(40)); } }
------解决方案--------------------
public class Test { public static void main(String[] args) throws Throwable { int min = 2; for (int i=4; i<=40; i+=2) { //求分母的最小公倍数 min = getMinTimes(min, i); } int sum = 0; for (int i=2; i<=40; i+=2) { //通分分子求和, 上面这里写错了,是i+=2,不是每次递增1 sum += min/i; } System.out.printf("%d/%d=%.4f\n", sum, min, ((double)sum)/min); //输出结果 double n = 0; for (int i=2; i<=40; i+=2) { //检验结果,上面这里写错了 n += ((double)1)/i; } System.out.printf("%.4f\n", n); } public static int getMinTimes(int a, int b) { //求两个数的最小公倍数 int a1 = a, b1 = b; int mod = a%b; while (mod != 0) { a = b; b = mod; mod = a%b; } return (a1*b1)/b; } }
------解决方案--------------------
//题目:1/2+1/4+1/6+1/8+.........+1/40的和,求java算法, public class Test { public static void main(String[] args) { float sum = 0 ; //int i ; for ( float i = 2 ; i <= 40 ; i += 2 ) sum += 1 / i ; System.out.println ("1/2+1/4+1/6+1/8+.........+1/40 = " + sum ); } }
------解决方案--------------------
public class B { public static void main(String[] args) { long[] result = new long[]{1,2}; for(int i = 1 ; i < 20; i++){ result = sum(1, i*2 + 2 , result); } System.out.println(result[0] + "/" + result[1]); } private static long[] sum(long fz,long fm, long result[]){ long[] result1 = new long[2]; result1[0] = result[0] * fm + fz * result[1]; result1[1] = result[1] * fm; long max = 1; for(long i = 1 ; i <= result1[0]; i++){ if(result1[0]%i == 0 && result1[1]%i ==0){ max = i; } } if(max != 1){ result1[0] = result1[0]/max; result1[1] = result1[1]/max; } System.out.println(result1[0] + "/" + result1[1]); return result1; } }
------解决方案--------------------