1

我怎样才能使我的代码

class Factorial {
    public static void main(String args[]) {
        int n, c, fact = 1;  

        for ( c = 1 ; c <= 5 ; c++ ) {
            fact = fact*c;
            System.out.println(fact);
        }
    }
}

看起来像这样

X X! 
1 1 
2 2 
3 6 
4 24 
5 120
4

8 回答 8

5
System.out.println(c+" "+fact);
于 2013-05-03T14:35:18.673 回答
2

您可以使用以下代码。

您可以让 System.out.println() 在新行上打印它,并让 System.out.print() 在同一行上打印内容。

class Factorial {
    public static void main(String args[]) {
        int n, c, fact = 1;  

        System.out.println("x x!");
        for ( c = 1 ; c <= 5 ; c++ ) {
            fact = fact*c;
            System.out.println(c + " " +fact);
        }
    }
}
于 2013-05-03T14:34:48.340 回答
2

另一个解决方案:

private static final String TEMPLATE = "%s %s";

public static void main(String args[]) {
    int n, c, fact = 1;
    System.out.println(String.format(TEMPLATE, "X", "X!"));
    for ( c = 1 ; c <= 5 ; c++ ) {
        fact = fact*c;
        System.out.println(String.format(TEMPLATE, c, fact));
    }
}
于 2013-05-03T14:41:23.007 回答
1

尝试这个 :

  public static void main(String args[]) {
    int n, c, fact = 1;


    System.out.println("X X! ");
    for (c = 1; c <= 5; c++) {
        fact = fact * c;

        System.out.println(c + " " + fact);
    }
于 2013-05-03T14:35:16.617 回答
1
System.out.println(c+" "+fact);
于 2013-05-03T14:36:02.530 回答
0

尝试

for ( c = 1 ; c <= 5 ; c++ ) {
            fact = fact*c;
            System.out.println(c + " " +fact);
        }
于 2013-05-03T14:38:24.743 回答
0
class Factorial {
    public static void main(String args[]) {
        int n, c, fact = 1;
        for ( c = 1 ; c <= 5 ; c++ ) {
            fact = fact*c;
            System.out.print(c+"! = "+fact+(c==5?".":", "));
        }
    }
}
于 2013-05-03T14:44:08.683 回答
-1

不确定您是否只是询问格式化一行中的输出,或者您想要进行一些逻辑更改:

为了在一行中格式化输出,这里是更新的代码:

       public class Factorial {
       public static void main(String args[]) {
            int n, c, fact = 1;  

            for ( c = 1 ; c <= 5 ; c++ ) {
                fact = fact*c;
                System.out.print(fact);
                System.out.print(" ");
            }
        }
}
于 2013-05-03T14:37:16.057 回答