-1

我一直在通过各种渠道自学 C。我发现的练习之一是过去一年的 cs50 问题集(可在此找到,位于Bad Credit标题下)。从本质上讲,我已经解决了这个问题,但意识到我正在执行相同的步骤两次,也许可以将该步骤包装在一个函数中以供重用。

我的问题是我不确定如何定义对尚未指定的数组的返回。或者,就此而言,如果这是一个好主意。我认为如果我能让它工作,重用代码将是一件好事,但我不知道该怎么做。

如下代码所示,问题是取一个长数字,分隔每个单独的数字,并执行一些数学运算来进行校验和。这step1在下面的代码中返回。循环在这里完成了繁重的do/while工作,我想做的是对 in 中的元素做同样的事情,step1并将它们返回到step2或任何其他变量中。

long long num = 378282246310005;
int step1[10];
int step2[10];

do {
    int i = 0; 
    step1[i] = num % 10; // this returns to one array
    num /= 10;
    i++;
   } while (num != 0);

我意识到这对这个问题没什么大不了的。我只是决定,如果可能的话,知道如何去做会很好。

4

2 回答 2

2

I'll take you through the steps. Here's your code:

do {
    int i = 0; 
    step1[i] = num % 10;
    num /= 10;
    i++;
} while (num != 0);

First, an error. The i variable should be initialized and declared outside the loop, otherwise i == 0 every single time you go through the loop.

int i = 0; 
do {
    step1[i] = num % 10;
    num /= 10;
    i++;
} while (num != 0);

This should be recognizable as the expanded version of a for loop, so:

for (int i = 0; num != 0; i++, num /= 10)
    step1[i] = num % 10;
// note: different for case num == 0

Then, if you want to turn it into a function,

void get_digits(int digits[], long long num) {
    for (int i = 0; num != 0; i++, num /= 10)
        digits[i] = num % 10;
}

A long story short, when you pass an array to a function in C, the array doesn't get copied so you can change the array inside the function and see those changes outside the function. (Long version: when arrays are function parameters they decay into pointers.)

Final note: you will need 19 elements in the array, not 10. So:

long long num = 378282246310005;
int step1[19];
get_digits(step1, num);
于 2013-07-29T03:58:45.650 回答
1

您可以通过引用传递数组,如下所示:

//Number to checksum is num
//Array to store checksum is arr
//Maximal length of arr is n
void checksum(long long num, int arr[], int n){
  int i = 0; 
  do {
    arr[i] = num % 10; // this returns to one array
    num /= 10;
    i++;
    if(i==n) return; //break before we overflow array
  } while (num != 0);
}

请注意,您的代码可能不安全,因为您最终可能会写入超出您为其分配的内存的数组的一部分。也就是说,您定义int step1[10]但最终可能会写入step[11].

另外,你把你int i=0的圈子困在了里面。我以为你想要它在外面。

于 2013-07-29T03:58:25.547 回答