我正在寻找一些关于我的阶乘方法的帮助。我似乎无法正确地总结它。
我只需要接受1到12之间的任何数字,然后对乘法求和...并返回求和。
用户选择:5 1 * 2 * 3 * 4 * 5 = 120
package cit130hmw07_laginess;
import java.util.Scanner;
public class CIT130HMW07_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please select a number between 0 and 12:");
int factorial = input.nextInt();
sumFactorials(factorial);
int facSum = sumFactorials(factorial);
System.out.println("");
System.out.println("Your results are: " + facSum);
System.out.println("");
}//main
public static int sumFactorials(int factorial)
{
int results = 1;
for(int i = 1; i <= factorial; i++)
results = results * factorial;
return results;
}//factorials
}//class
答案 0 :(得分:0)
代码中的一些小缺陷。在相应的声明中查找注释中的错误,以及它们在下面的代码中的更正。注意不需要的额外线条。您应始终使用尽可能少的行编写代码,而不会影响可读性(即使用适当的缩进)。
package cit130hmw07_laginess;
import java.util.Scanner;
public class CIT130HMW07_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please select a number between 0 and 12:");
int factorial = input.nextInt();
//sumFactorials(factorial);
//this line was not required.
int facSum = sumFactorials(factorial);
//System.out.println("");
//not required when you can use delimiters inside println
System.out.println("\nYour results are: " + facSum + "\n");
//System.out.println("");
//same as before.
}//main
public static int sumFactorials(int factorial)
{
int results = 1;
for(int i = 1; i <= factorial; i++)
//results = results * factorial;
//this was where your code was not correct.
//Correct :
results = results * i;
return results;
}//factorials
}//class
在println中,我使用了分隔符(查找 \ n )来最小化打印语句。
答案 1 :(得分:0)
检查您的错误评论:
唯一的修正是:
结果=结果* I;
休息是一些不必要的东西;
包cit130hmw07_laginess;
import java.util.Scanner;
public class CIT130HMW07_Laginess
{
public static void main(String[] args)
{
Scanner input = new Scanner(System.in);
System.out.println("Please select a number between 0 and 12:");
int factorial = input.nextInt();
//sumFactorials(factorial);
int facSum = sumFactorials(factorial);
//System.out.println("");
System.out.println("Your results are: " + facSum);
//System.out.println("");
}//main
public static int sumFactorials(int factorial)
{
int results = 1;
for(int i = 1; i <= factorial; i++)
//results = results * factorial;
results=results*i;
return results;
}//factorials
}//class