c - 为什么我没有得到想要的输出?

标签 c string

问题是写出要求的斐波那契词。例如,如果输入为 0,则 f(0) = a,如果为 1,则 f(1) = b,类似地,f(2) = ba,f(3) = bab,f(4) = babba 等等。我编写了以下代码来查找 Ubuntu 18.04 LTS 终端上的输出。我得到 n=0,1,2,3 的正确输出。但是对于 n=4 我得到的是 babb 而不是 babba。我也试过调试,但找不到代码哪里出错了。请帮助我找出错误。

#include <stdio.h>
#include <string.h>
void fibonacci(int n);
int main()
{
    int x;
    printf("Enter the fibonacci nword number you want to see:(f(x), f(0) is the starting element.):\n");
    scanf("%d",&x);
    printf("Required Word is:\n");
    fibonacci(x);
    return 0;
}

void fibonacci(int n)
{
    int i,j=0;
    char *p,*q,*r;
    if(n==0)
    {
        printf("a\n");
    }
    else if(n==1)
    {
        printf("b\n");
    }
    else 
    {
        char str1[100] = "a";
        char str2[100] = "b";

    char str3[100];
        p = str1;
        q = str2;
        r = str3;
        for(i=0;i<n-1;i++)
        {
            *r = *q;
            strcat(str2,str1);
            *p = *r;
        }
        printf("%s\n",str2);
    }
}

最佳答案

首先回答“为什么我没有得到想要的输出”的主要问题:

因为你不知道自己在做什么。

您静态声明了 3 个 char[] 变量,将它们分配给 char* 类型的指针,甚至没有正确使用它们。

让我们分析一下您的代码的一部分:

for(i=0;i<n-1;i++)
{
    *r = *q;
    strcat(str2,str1);
    *p = *r;
}

你所做的基本上是:

  • 分配 str3[0] = 'b'(在 *r = *q 中)
  • 将str1的内容复制到str2中,所以,第一次运行的时候是“ba”
  • 分配 str1[0] = 'b'(在 *p = *r 中)
  • 然后,重复将“b”连接到 str2,因为现在两个 str1 都只包含一个“b”。

这样做,对于任何超过 4 的东西,你只会得到“babbbbbbbbbb”...

我的建议:如果您打算静态声明一些变量,请停止使用指针来访问它们。尝试将 str1/str2 作为 vector 访问。

关于c - 为什么我没有得到想要的输出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56555396/

相关文章:

c - [anon]在pmap linux cmd中意味着什么

java - 是什么让 String 不可变?

php mp3字符串错误

c - 如何读取文件直到遇到换行符

c - 非阻塞 tcp 套接字如何通知应用程序发送失败的数据包。

c - 如何在 Visual Studio Code 中运行 C 程序?

c - 可以生成多少个参数以及为什么会生成它们?

regex - 使用 Perl 从多行字符串中提取文本

python - 如何在 Python 2 中将字符串更改为 Unicode?

php - 检查 $_POST-value 是否为空