简化因子

时间:2014-09-16 12:03:30

标签: java factorial

这是我显示阶乘的代码。但我认为这太长了。如何缩短代码?反馈将不胜感激。谢谢!

这是示例输出:

6! = 5 * 4 * 3 * 2 * 1 = 720

这是我的代码:

import java.io.*;
public class Factorial {

   public static void main (String args[]) throws IOException
   {
BufferedReader br = new BufferedReader(new InputStreamReader(System.in));

int f = 1;

System.out.print("Enter number: ");
int num = Integer.parseInt(br.readLine());
int temp3 = num;
String temp [] = new String [num];

while (num >= 1)
{
    f = num * f;
    num = num - 1;
}

   for (int x=1; x<temp3; x++)
   {
    temp[x]= "" + Integer.toString(x);
   }


StringBuffer result = new StringBuffer();
for (int i = temp3 - 1; i >= 1; i--) {
    result.append(temp[i]);

    if (i > 1)
    {
        result.append("*");
    }

}

   System.out.print(temp3 + "! = " + result.toString() + " = " + f);

   }


}

1 个答案:

答案 0 :(得分:3)

而不是让您的代码更短,专注于可读性

在缩短之前需要修复的一些事情

  1. Indendation
  2. 变量命名:temp,x,f等没有意义
  3. 使用正确的数据类型:int将导致溢出
  4. 还尝试自己编写代码而不是复制代码段

    for (int i = temp3 - 1; i >= 1; i--) {
        result.append(temp[i]);
    
        if (i > 1)
        {
    

    据我了解,这个世界上有两种类型的人

    1. 谁在条件
    2. 的同一行开始花括号
    3. 谁开始下一行
    4. 如何在3行间隙内同时使用?