Ano*_*DCX 9 c# for-loop console-application factorial
我正在处理来自CodeChef的问题,我需要计算n个数字的阶乘.
用户输入一个数字,该数字确定执行因子计算的总数,然后输入要计算的数字.
我的问题在于乘法本身.例如,如果我有一个int == 5那么结果将是20(它将仅由最后一个因子计算n,而不是全部计算n)
这是存在问题的地方:
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index
for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x
_result[x] = _numbersToProcess[x] * y;// Multiply x by y then add to array
}
}
Run Code Online (Sandbox Code Playgroud)
外循环定义要执行的计算数.
内循环通过迭代每个索引_numberToProcess并将其乘以小于要计算的数的每个数来来计算阶乘.
问题是因子计算会覆盖自身,
例如:
阶乘5的结果:20但它应该是120(它会覆盖自己,直到到达最后一个乘数)
所以我尝试了以下方法:
_result[x] = _numbersToProcess[x] *= y;
Run Code Online (Sandbox Code Playgroud)
这显然是一样的 _numbersToProcess[x] = _numbersToProcess[x] * y;
但这给出了一个完全不同的结果:
如果我们再次输入5,那么这将导致输出-1899959296.
我知道我可以轻松地从其他提交中复制和粘贴,但我想知道为什么我的方法不会产生正确的输出.
以下是整个方法:
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate
int[] _numbersToProcess = new int[_numbers];// Array of inputs
int[] _result = new int[_numbers];
int i = 0;
while(i < _numbersToProcess.Length) {
_numbersToProcess[i] = int.Parse(Console.ReadLine());
i++;
}
for(int x = 0; x < _numbersToProcess.Length; x++) {// Loop throuigh Array by index
for (int y = 1; y < _numbersToProcess[x]; y++) {// Y is equal to less than index x
_result[x] = _numbersToProcess[x] *= y;// Multiply x by y then add to array
}
}
for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x
Console.WriteLine(_result[n]);// Write to console
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
int _numbers = int.Parse(Console.ReadLine());// Get number of ints to calculate
int[] _numbersToProcess = new int[_numbers];// Array of inputs
int[] _result = new int[_numbers];
int i = 0;
while(i < _numbersToProcess.Length) {
_numbersToProcess[i] = int.Parse(Console.ReadLine());
i++;
}
for (int x = 0; x < _numbersToProcess.Length; x++)
{// Loop throuigh Array by index
int fact = 1;
for (int y = 1; y <= _numbersToProcess[x]; y++)
{// Y is equal to less than index x
fact = fact*y;
}
_result[x] = fact;
}
for (int n = 0; n < _result.Length; n++) {// Y is equal to less than index x
Console.WriteLine(_result[n]);// Write to console
}
Console.ReadLine();
Run Code Online (Sandbox Code Playgroud)
问题出在你的内部 for 循环上。在这里,你总是覆盖结果数组。
即对于 y=5;内部for循环执行5次。
iteration -1 :
y=1,
_numbersToProcess[5]=5
_result[x]=5
iteration -2 :
y=2,
_numbersToProcess[5]=10
_result[x]=10
iteration -3 :
y=3,
_numbersToProcess[5]=30
_result[x]=30
.
.
.
.
.
Run Code Online (Sandbox Code Playgroud)
因此,当您的 _numbertoprocess[5] 发生变化时,它会进行 12 次迭代,并在它达到小于 0(即 -1899959296)时停止。
iteration 12:
_numbertoprocess[5] = -1899959296.
Run Code Online (Sandbox Code Playgroud)
即,您每次在内部 for 循环中都会更改 numbertoprocess 。
您可以通过添加来验证它
Console.WriteLine(y);
Console.WriteLine(_numbersToProcess[x]);
Console.WriteLine(_result[x]);
Run Code Online (Sandbox Code Playgroud)
在你的内部 for 循环中。
| 归档时间: |
|
| 查看次数: |
1195 次 |
| 最近记录: |