【问题标题】:Program that computes the nth element of a number series given by a formula计算公式给出的数列的第 n 个元素的程序
【发布时间】:2022-11-01 22:00:45
【问题描述】:

编写一个名为 cpSeries 的方法/函数,它计算一系列数字中的第 n 个元素,由公式给出:a(n) = (a(n-1))2+a(n-2) 当:n>1并假设: a(1)=1, a(0)=0 请注意,系列的索引从 0 开始。

我已经编写了上面的代码,但它运行了无限时间,我不知道如何修复它以计算第 n 个元素。

有任何想法吗?我必须只使用函数来解决这个问题。

# include <stdio.h>

int cpSeries(int n)
{    
    int Nthterm = 0;
    int i;
    
    if (n==0) {
        cpSeries(0) == 0;
    }
    else if (n==1) {
        cpSeries(1) == 1;
    }
    for (i=0; i<=n; i++){
        Nthterm = cpSeries((n-1))*cpSeries((n-1)) + cpSeries((n-2));
        return Nthterm;
    }
}

int main()
{
    int n=6;
    printf("The Nth term of the series is: %d",cpSeries(n));
}

【问题讨论】:

  • 你写cpSeries(0) == 0;时是指return 0;吗?
  • 是的。我以为是一样的。

标签: c


【解决方案1】:

您的最终条件只是再次调用该函数,而不是返回 0 或 1。

代替

if (n==0) {
    cpSeries(0) == 0;
}
else if (n==1) {
    cpSeries(1) == 1;
}

利用

if (n==0) {
    return 0;
}
else if (n==1) {
    return 1;
}

【讨论】:

    猜你喜欢
    • 2019-01-15
    • 1970-01-01
    • 2011-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多