c - 为什么这段代码打印第 n 个数字给出运行时错误?

标签 c

我们必须打印一系列的第 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/

相关文章:

C- 窗口/打印不出现

c - 函数返回类型语法

c - 在不同类型的变量之间分配共享内存时出现段错误

c - 由于 SIGINT 导致的部分写入

计算两个数的回文数

c - malloc 不确定性行为

c - 静态变量的地址是否可以被其他文件访问

c - 信号量实现

c - 如何在函数调用中使用宏?

c - 函数 swab 的隐式声明