问题描述
int factorial(int x)
{
int i;
for(i=1; i < x; i++)
x *= i;
return x;
}
他们举了一个例子:
they gave an example of:
int a=5, b;
b = factorial(a);
并说:在这个短程序结束时,变量b将包含120,因为将使用参数5调用阶乘函数并返回120.
有人可以解释b是多少是120吗?
你能帮我看一下代码吗?
factorial(a)是什么意思?
将a的值替换为 x * =我
?
我尝试过:
没什么,我只是在读一本关于它的书,我不明白。
and said: "At the end of this short program, the variable b will contain 120, since the factorial function will be called with the argument of 5 and will return 120."
Can some one explain how b is 120?
Can you also help me read the code?
What do they mean by " factorial(a) " ?
Did the substitute the value of a into " x *= i
" ?
What I have tried:
Nothing, i was just reading a book about it and i don't understand.
推荐答案
int factorial(int x)
{
int i;
for(i=1, i < x, i++) // set i to the value 1, while i is less than x
x *= i; // multiply x by the value of i [1 .. x-1]
// add 1 to i and repeat.
return x; // return the calculated value of x
// so if x starts at 5
// it becomes x * 1 ... 5 ... i starts at 1, x starts at 5
// x * 2 ... 10 ... i is now 2 so the loop will have another 7
// iterations to perform
// x * 3 ... 30 ... but i is now 3 so it will have another 26
// x * 4 ... 120 ... i is now 4 and x is 120, so the loop will never terminate
}
阶乘函数只是一个数学特征。
The factorial function is just a mathematical feature.
1! == 1
2! == 1 * 2 == 2
3! == 1 * 2 * 3 == 6
4! == 1 * 2 * 3 * 4 == 24
5! == 1 * 2 * 3 * 4 * 5 == 120
6! == 1 * 2 * 3 * 4 * 5 * 6 == 720
...
你的代码中有一个函数,它传递一个数字(在一个名为 x )并返回该数字的因子,通过使用一个简单的循环来进行乘法。 (好吧,你会,如果那会编译 - for
循环使用分号,而不是逗号 - 如果它能正常工作 - 它不会:算法错误地实现了)
因此,当您修复 factorial
函数时,您可以在其中使用它的名称来调用它代码:
What you have in your code is a function which is passed a number (in a variable called x
) and which returns the Factorial of that number, by using a simple loop to do the multiplication. (Well, you would, if that would compile - for
loops use semicolons, not commas - and if it would work correctly if it did - which it won't: the algorithm is wrongly implemented)
So when you fix the factorial
function you can call it by using it's name in your code:
b = factorial(a);
这会导致代码分支到阶乘函数,复制值在 a
进入 x
时到达那里,然后返回原始代码并将值放入阶乘返回(通过 return
语句)到变量 b
这就像你经常发布的文本列表一样,以节省你每次输入它们:你把它们放在记事本中,当你想发布一个时,你从记事本中复制它并粘贴到你的浏览器中。每个文本片段都是一个函数,copy'n'paste正在调用它进入你的帖子。有意义吗?
and that causes your code to "branch off" to the factorial function, copying the value in a
into x
when it gets there, then "comes back" to the original code and puts the value that factorial returned (via the return
statement) into the variable b
It's like having a list of bits of text you post often to save you typing them out each time: you keep them in Notepad and when you want to post one, you copy it from Notepad and paste it into your browser. Each text fragment is a function and copy'n'paste is "calling" it into your post. Make sense?
这篇关于我不懂基本的C函数示例。请帮忙的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!