【问题标题】:My input in scanf is not working, process is returned and I don't get any output我在 scanf 中的输入不起作用,返回进程并且我没有得到任何输出
【发布时间】:2020-10-02 08:09:48
【问题描述】:

运行此程序时未获得斐波那契数列。在scanf中输入后整个过程终止。

#include <stdio.h>
#include <stdlib.h>

int fibonacci(int);

int main()
{
    int n, i = 0, c;
    printf("Print the fibonacci series");
    scanf("%d", n);
    for (c = 1; c <= n; c++)
    {
        printf("%d\n", fibonacci(i));
        i++;
    }
    return 0;
}

int fibonacci(int n)
{
    if (n = 0)
        return 0;
    else if (n = 1)
        return 1;
    else
        return (fibonacci(n - 1) + fibonacci(n - 2));
}

【问题讨论】:

    标签: c recursion scanf fibonacci


    【解决方案1】:

    使用 scanf 你需要给出变量的地址。

       scanf("%d",&n); <= need to give the address of the integer
    

    您可以在此处找到一些示例: http://www.cplusplus.com/reference/cstdio/scanf/

    【讨论】:

    • 我做到了,但现在还有另一个问题,如果我将输入设为 5 而不是斐波那契数列,请帮助@Robert
    【解决方案2】:

    正如您在Robert's answer 中已经告知的那样,scanf 需要每个格式说明符的地址。因此,如果提供了格式说明符 %d,则需要整数的地址:scanf 将在那里写入值。

    如果n 是包含整数的变量,则&amp;n 是它的地址。传递不是地址的东西会导致麻烦:它是未定义的行为,可能会导致分段错误。


    您的斐波那契生成器也存在一些问题。我想你想打印序列中的第 n-th 个数字,但是你迭代 n 次调用 fibonacci() 函数(它只返回最后一个值)总是带有参数i,其值为0。

    fibonacci 函数中,您尝试检查退出条件,但注意

    if (n = 0)
        return 0;
    

    不检查n 的值;它执行分配n 的值为 0,条件为 false)。所以它会进行下一个“测试”

    if (n = 1)
        return 1;
    

    这也是一个赋值,1被赋值给n,所以条件为真,返回1。这就是您看到 1 n 次的原因。


    为了让它工作

    • 更正scanf 问题
    • c 传递给fibonacci()
    • 更正函数以便测试值(== 而不是=
    #include <stdio.h>
    #include <stdlib.h>
    
    int fibonacci(int);
    
    int main()
    {
        int n, c;
        printf("Print the fibonacci series\n");
        scanf("%d", &n);
        for (c = 1; c <= n; c++)
        {
            printf("%d\n", fibonacci(c));
        }
        return 0;
    }
    int fibonacci(int n)
    {
        if (n == 0)
            return 0;
        else if (n == 1)
            return 1;
        else
            return (fibonacci(n - 1) + fibonacci(n - 2));
    }
    

    【讨论】:

    • 您可以删除无用的i = 0,i++;
    • 谢谢@Stef,你是对的。我没有花足够的精力清理杂物。
    【解决方案3】:

    您错过了scanf 语句中的&amp; 符号,而且我认为您对斐波那契函数中的赋值运算符= 和逻辑等于== 感到困惑。

    #include <stdio.h>
    #include <stdlib.h>
    
    int fibonacci(int);
    
    int main()
    {
        int n, i = 0, c;
        printf("Print the fibonacci series");
        scanf("%d", &n);
        for (c = 1; c <= n; c++)
        {
            printf("%d\n", fibonacci(i));
            i++;
        }
        return 0;
    }
    
    int fibonacci(int n)
    {
        if (n == 0)
            return 0;
        else if (n == 1)
            return 1;
         else
            return (fibonacci(n - 1) + fibonacci(n - 2));
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-02-23
      • 2018-05-30
      • 1970-01-01
      • 1970-01-01
      • 2023-01-30
      • 2020-10-19
      • 1970-01-01
      相关资源
      最近更新 更多