我刚开始接触C编程(虽然我有Java的经验)。读了一些教程后,我决定开始在 Coderbyte 上解决编码挑战。
我尝试的第一个挑战是这个:
挑战
编写函数 FirstFactorial(num),将传递给它的参数 num 返回其阶乘。例如:如果 num = 4,则您的程序应返回 (4 * 3 * 2 * 1) = 24。对于测试用例,范围将介于1和18之间,输入始终为整数。
示例测试用例
输入:4
输出:24输入:8
输出:40320
我的解决方案:
#include <stdio.h>
void FirstFactorial(int num[]) {
int i = num -1;
for(i ; i > 0; i--) {
num = num * i;
printf("%d",i);
}
printf("\t %d", num);
}
int main(void) {
// disable stdout buffering
setvbuf(stdout, NULL, _IONBF, 0);
// keep this function call here
FirstFactorial(gets(stdin));
return 0;
}
输入参数的值为:8
错误信息:
main.c: In function 'FirstFactorial':
main.c:5:11: warning: initialization makes integer from pointer without a cast [-Wint-conversion]
int i = num -1;
^~~
main.c:8:15: error: invalid operands to binary * (have 'int *' and 'int')
num = num * i;
^
main.c: In function 'main':
main.c:23:18: warning: passing argument 1 of 'FirstFactorial' makes pointer from integer without a cast [-Wint-conversion]
FirstFactorial(8);
^
main.c:3:6: note: expected 'int *' but argument is of type 'int'
void FirstFactorial(int num[]) {
^~~~~~~~~~~~~~
exit status 1
看起来有一些问题,我有几个问题:
I've never heard of
gets(stdin)
. I looked upgets()
, and the glibc documentation says the function returns achar*
. How can I pass it to a function that takes anint
?It looks like
int i = num -1;
is initializing
i
as 4 and not 7. Why?The for loop seems to be decrementing
i
correctly (i
= 7, 6, 5, 4, 3, 2, 1). But this statement:num = num * i;
is generating an error. What is wrong with it? It looks like a normal multiplication.
gets()
,因为在当前版本的C中,它已经不存在了,这是有充分理由的。使用gets()
无法编写正确/安全的代码。 - user2371524gets
函数。它很危险,容易发生缓冲区溢出,因此已被从 C 规范中移除。相反,使用例如fgets
函数。 - Some programmer dudescanf("&d", &var);
代替读取整数。 - HolyBlackCat