我怎样才能打印出方程而不是计算

时间:2013-11-07 00:50:26

标签: java

赋值是编写一个名为fractionSum的方法,它接受一个整数参数n,并返回序列前n个项之和的double:1 +(1/2)+(1/3)+(1 / 4)+(1/5)+ ... +(1 / n)您可以假设参数n是非负的。

import java.util.Scanner;

public class Fraction { 
    public static void main(String[] args) {
        Scanner console = new Scanner(System.in); 
        System.out.println("Enter an integer");
        int a = console.nextInt();

        fractionSum(a);
    }

    public static void fractionSum (int a) {
        for(int i = 1; i<=a; i++) { 
        double sum = (1/i);
        System.out.println(sum);
        } 
    }
}

它现在所做的只是计算实际值

如何打印出“1 + 1/2 + 1/3 + 1/4 + ... + 1 / n”

2 个答案:

答案 0 :(得分:0)

public static void fractionSum (int a) {
        System.out.print("1");
        double sum = 1;
        for(int i = 1; i<=a; i++) { 
            System.out.print(" + 1/" + i);
            sum += (1/(double)i);
        } 
        System.out.print("/n" + sum);
    }

答案 1 :(得分:0)

经过测试并且有效:

public static void fractionSum (int a) 
{
    for (int i = 1; i <= a; i++) 
    {
        if (i != 1)
            System.out.print(" + 1/" + i);
        else 
            System.out.print("1");
    } 
}