2013-10-27 115 views
1
import java.util.*; 

//Creates a program which allows the user to find the factorial of a number 

public class forLoop { 
    public static void main (String [] args) { 

     Scanner input = new Scanner(System.in); 

     System.out.println("Enter the number you want the factorial from: "); 
     int number = input.nextInt(); // user input 
     input.close(); 

     int result_2 = getFactorial(number); //initializes getFactorial method 
     System.out.println("The factorial of " + number + " is " + result); //prints results 

     } 

    public static int getFactorial (int num1) { 
     int result; 

     for (int times = num1; times <= 1; times--) { //repeats loop until times <=1 

      result = num1 * (num1 - 1); //does the factorial equation 

     } 

     return result; // returns results (here is the problem) 
    } 
} 

回答

3

编译器无法假定循环至少会执行一次 - 这是result分配的必要条件。如下解决该问题的result

更改声明:

int result = 1; 

这将有助于你的代码编译,但它不会在计算阶乘修复逻辑错误:目前,你的循环将无限期因为运行错误的循环条件。

您应该将1的数字乘以num1(含)。更改环路条件,以便times >= 1而不是times <= 1,并将环路主体更改为result *= times以解决此错误。

+3

IMO,'INT结果= 1;因为程序是大约阶乘'可能会更好。主要方法还有另一个错误。打印最终结果的SOP。 – SudoRahul

+0

@ R.J有一个逻辑错误,我会写更多关于它。 – dasblinkenlight

1

您需要并初始化这个变量:

int result; 

像这样:

int result = 0; //Which ever intial value you want 

因为编译器将无法确定,对于循环将一直执行。

0

,因为你是分配函数的返回值result_2,你应该打印的,而不是结果

尝试

System.out.println("The factorial of " + number + " is " + result_2); 

而你需要使用它们

0

的前初始化局部变量for循环的条件不正确

它应该是

for (int times = num1; times >= 1; times--) 
{ 

      result *= times; //this wil calculate right factorial 

} 

for循环

0
int result; 

    for (int times = num1; times <= 1; times--) { //repeats loop until times <=1 

     result = num1 * (num1 - 1); //does the factorial equation 

    } 

该块导致错误之前还初始化结果为1。如果循环不会由于这种运行甚至一度

次< = 1

条件的Java不会有什么在这里印

System.out.println("The factorial of " + number + " is " + result); 

所以这里来初始化需要哪些充当打印的默认值。 因此该解决方案将取代

int result; 

int result=1; // note that I am not initializing with 0 as that will cause every factorial to become zero. 

有在你的代码中的另一个错误,而不是

times <= 1 

应该

times >= 1 

你合作德可能不会运行这个错误一次。

0

只是初始化int result的东西:

int result = 0; 

因为你的循环没有执行(times已经大于1),它试图返回一个未初始化的变量。