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)
}
}
Q
结果没有初始化?
1
A
回答
3
编译器无法假定循环至少会执行一次 - 这是result
分配的必要条件。如下解决该问题的result
更改声明:
int result = 1;
这将有助于你的代码编译,但它不会在计算阶乘修复逻辑错误:目前,你的循环将无限期因为运行错误的循环条件。
您应该将1
的数字乘以num1
(含)。更改环路条件,以便times >= 1
而不是times <= 1
,并将环路主体更改为result *= times
以解决此错误。
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),它试图返回一个未初始化的变量。
相关问题
- 1. NSDictionary初始化结果“EXC_BAD_ACCESS”
- 2. PHP初始化,如果没有设置
- 3. ObjectInputStream没有初始化
- 4. 类没有初始化器?
- 5. 类没有初始化
- 6. 的TextView没有初始化
- 7. 属性没有初始化
- 8. Accumulo没有被初始化。
- 9. skrollr.min.js没有初始化
- 10. JqGrid没有初始化
- 11. 初始化嵌入式结构当在父初始化没有控制
- 12. fortran结果变量未初始化
- 13. 意外的初始化结果
- 14. 结果初始化的是未使用
- 15. LINQ结果到对象初始化器
- 16. 初始化结构
- 17. 初始化结构
- 18. 初始化结构
- 19. 结构,初始化
- 20. 初始化结构
- 21. 初始化结构
- 22. 结构初始化
- 23. 虽然初始化光标数据库没有初始化
- 24. 从初始化程序列表初始化,但没有{{{{{{{{...}}}}}}}}?
- 25. 在函数中初始化,并没有在主要初始化
- 26. C++结构体初始值初始化
- 27. 初始化含有初始化列表
- 28. 初始化嵌套结构没有定义的所有字段
- 29. 初始化结构的私有成员
- 30. 初始化所有结构成员
IMO,'INT结果= 1;因为程序是大约阶乘'可能会更好。主要方法还有另一个错误。打印最终结果的SOP。 – SudoRahul
@ R.J有一个逻辑错误,我会写更多关于它。 – dasblinkenlight