[英]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.