我们必须打印一系列的第 n 项,其前三项给出为 a, b, c
并且第 n 项是前三项的总和。
#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>
//Complete the following function.
int find_nth_term(int n, int a, int b, int c) {
//Write your code here.
int i, arr[n];
arr[0] = a;
arr[1] = b;
arr[2] = c;
if (n >= 3 && i <= n) {
arr[i] = arr[i - 1] + arr[i - 2] + arr[i - 3];
//using recursion to find nth term
return find_nth_term(n, a, b, c);
} else {
return;
}
}
int main() {
int n, a, b, c;
scanf("%d %d %d %d", &n, &a, &b, &c);
int ans = find_nth_term(n, a, b, c);
printf("%d", ans);
return 0;
}
最佳答案
如果函数中的 if
语句的计算结果为 False
,则您不会返回
任何内容。您已将函数的返回
类型设置为int
,但您实际上并未返回
任何内容。
将该行更改为:
return (a + b + c);
此外,正如 @Inrin 在评论中指出的那样,您永远不会初始化 i
。
关于c - 为什么这段代码打印第 n 个数字给出运行时错误?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51684540/