繁体   English   中英

如何将我的 function 返回 C 中的数组?(代码修复)

[英]How to turn my function returns an array in C?(code to fix)

我试图让一个数组存储我输入的每个数字。

有些喜欢:输入号码:687544

并以数组形式返回,例如: 6 8 7 5 4 4

我只弄清楚如何在下面的“store (num)”function 中按顺序存储 nums:

#include<stdio.h>

int store(int num);

int main()
{
    int num;

    printf("Enter number: ");

    scanf("%d",&num);    

    return store(num);
}

int store(int num)
{   
    if(num!= 0)
    {
        int mod = num % 10;  //split last digit from number

        store(num/10);  //recuring it back to the right order

        printf("%i\n",mod); //divide num by 10. num /= 10 also a valid one 
    }
}

以下是我试过但没有工作的代码

#include<stdio.h>

int store(int num);

int main()
{
    int num,d;
    printf("Enter number: ");
    scanf("%d",&num);

    for(d=0; num<0;d++);
    {
        num /= 10;
    }

    int a[d];

    int i;

    for(i=0;i<d;i++){
        a[d]=store(num);
    }

    printf("%d \n",a[d]);
}

int store(int num)
{   
    if(num!= 0)
    {
        int mod = num % 10;  

        store(num/10);  

        return mod;
    }
}

意想不到的结果......

Enter number: 123

115183680

感觉我快到了,但我不知道哪一部分出了问题。 请问如何解决这个问题?

我只弄清楚如何在“store (num)”function 中按顺序存储 nums,但是我尝试扩展我的代码,结果不是我预期的。

这是您的代码,基于您编写的相同路由(使用递归调用)以及读取 int 和解析数字等

#include<stdio.h>
 
void store(int num, int* a, int* d);
int main()
{
     int a[10]; // int is 32bit, (Depending on compiler, you can not store more than 10 digit) log10(2**32) ~ 9.xx
     int num,d = 0;
     printf("Enter number: ");
     scanf("%d",&num);
     // the recursive function, should need the pointer to array, and the index which is currently parsing
     store(num, a, &d);
     
     // print your array till valid index,
     for(int i = 0; i< d; i++)
         printf("%d ",a[i]);
     printf("\n");
 }   
void store(int num, int* a, int* d)
{    
     if(num!= 0)
     {
         store(num/10, a, d);
         int mod = num % 10; 
         a[(*d)++] = mod;
     }   
} 

这是一个修改后的版本,其中包含对我所做更改的评论

int store(int num, int digit);

int a[20];  // Don't bother with dynamic allocation

int main()
{
    int num,d;
    printf("Enter number: ");
    scanf("%d",&num);

    int digit = 0;
    int i;
    digit = store(num, 0);

    // Always print at least 1 digit
    for(i=0; i< (digit ? digit : 1); i++){
        printf(" %d", a[i]);
    }
    printf("\n");
}

// Pass in which digit you are on
int store(int num, int digit)
{   
    if(num!= 0)
    {
        int mod = num % 10;
        int last = store(num/10, digit+1);  // next digit

        // Fill array right-to-left
        a[last - digit - 1] = mod;

        return last;
    }
    return digit;  // return number of digits
}

Output

prog$ ./foo
Enter number: 0
 0
prog$ ./foo
Enter number: 5
 5
prog$ ./foo
Enter number: 123
 1 2 3

请注意,如果您不需要全局数组,可以将其作为第三个参数添加到store 在这种情况下,不要忘记在 main 中初始化a[0]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM