【问题标题】:In C, computing an equation using user input values is not giving the expected result?在 C 中,使用用户输入值计算方程不会给出预期结果?
【发布时间】:2019-02-27 07:20:32
【问题描述】:

我正在为我的班级做作业,但我被卡住了。任务是:

编写一个递归程序来预先计算斐波那契数并将它们存储在一个数组中。斐波那契公式是 Fib(0) = 1,Fib(1) = 1 和 Fib(i) = Fib(i - 1) + Fib(i - 2)。将第 i 个斐波那契数存储在索引 i 处。有一个循环来读取 i 并打印 i 和第 i 个斐波那契数。使用 -1 退出循环。我的输出是错误的,但我不知道如何解决它。我已经尝试了一段时间,但我无法确定我的错误。

我的代码是

#include <stdio.h>  
double Fib[50]; //globally declared 
int fib(int i)
{               
    for(i=0; i<50; i++) //loop to scan 
    {   
        scanf("%lf", &Fib[i]); //scan and store numbers in an array
        if (Fib[i]==-1) //i =-1 will end loop
            break;
    }       
    Fib[i]= Fib[i-1]+Fib[i-2];//formula     
    if(Fib[i]==0||Fib[i]==1) //i=0 and i=1 will print 1
        Fib[i]=1;
    else if(i>1) //performs the operation with the formula
        printf("%d  %lf\n", i, Fib[i]);
}   
int main()
{
    int i=0;
    fib(i); 
return 0;    
}
Expected result:
user input: 4 10 20 15 5 -1
output:
4 5.000000
10 89.000000
20 10946.000000
15 987.000000
5 8.000000  

My output:
5  20.000000

【问题讨论】:

  • 关于您的代码的几点说明:为什么将i 作为参数传递给fib 函数,而不是将其定义为函数内部的局部变量?在循环之后,i 的值可以等于50,这是数组的超出范围。或者i 的值可能小于2,这意味着i - 1i - 2 可能超出范围。
  • 关于您的问题,您可能想做一些rubber duck debugging。考虑到您只有一个 single (并且是有条件的!)printf 调用,为什么您期望代码有多个输出?你的函数真的没有多大意义,而且它肯定不会计算斐波那契数列。我的猜测是你应该做一些 recursion (因为你显示的公式中使用了它)。

标签: c arrays loops math


【解决方案1】:

几点

  • 您的程序不是递归的
  • 首先使用递归函数计算所有 Fib,然后再计算 循环处理用户输入

下面的代码有处理用户输入的结构,做递归

#include <stdio.h>

// It would make sense for this to store unsigned long long instead of double
// because Fibonacci numbers are always positive integers
unsigned long long Fib[50];

// Your assignment specifically said use a recursive program to compute Fib.
// This is not a recursive function, but it is correct, I will leave the
// recursion for you to work out
void populateFib() {
    Fib[0] = 1;
    Fib[1] = 1;
    unsigned i;
    for (i = 2; i < 50; ++i)
        Fib[i] = Fib[i - 1] + Fib[i - 2];
}

int main() {
    // First compute Fib
    populateFib();

    // Deal with user input in an infinite loop
    for (;;) {
        int input;
        scanf("%d", &input);

        // Condition for breaking the infinite loop
        if (input == -1)
            break;

        // Sanity check the user won't read out of bounds
        if (input < 0 || input >= 50) {
            printf("No!\n");
            continue;
        }

        // Display what the user wants
        printf("%d %llu\n", input, Fib[input]);
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-15
    • 1970-01-01
    • 2020-02-10
    相关资源
    最近更新 更多