<分区>
我是 C 编程的新手(尽管我有 Java 经验)。阅读一些教程后,我决定开始解决 Coderbyte 上的编码挑战。 .
我尝试的第一个挑战是 this one :
Challenge
Have the function FirstFactorial(num) take the num parameter being passed and return the factorial of it. For example: if num = 4, then your program should return (4 * 3 * 2 * 1) = 24. For the test cases, the range will be between 1 and 18 and the input will always be an integer.
Sample Test Cases
Input: 4
Output: 24Input: 8
Output: 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
所以好像有几个问题,我有几个问题:
我从未听说过
gets(stdin)
。我查了一下gets()
,并且 glibc 文档说该函数返回一个char*
。如何将它传递给采用int
的函数?看起来像
int i = num -1;
正在将
i
初始化为 4 而不是 7。为什么?for 循环似乎正确地递减了
i
(i
= 7、6、5、4、3、2、1)。但是这个声明:num = num * i;
正在生成错误。它有什么问题?它看起来像一个普通的乘法。