我遇到了以下问题:
“在函数 main 中声明一个名为 num1 的整数数组,包含 30 个元素,并声明第二个名为 num2 的整数数组,包含 21 个元素。 为 num1 的每个元素分配一个 1 到 50 之间的随机数;打印数字。
在 for 循环
中,将前 21 个数字从 num1 复制到 num2。
在另一个 for 循环
中打印 num2 中的元素值,每行七个值。找到一种算法,可以从一个循环而不是 3 个循环打印它们。 ”
我已经能够将范围缩小到 2 个 for 循环,但是我很难尝试将所有内容放入一个 for 循环中。如果我不使用第二个 for 循环,我只是不确定如何将数组从 num1 复制到 num2 中。
这是我迄今为止所做的工作。它正确地打印了所有内容,但它是在 2 个 for 循环中,而不是 1 个。
for (j = 0; j < 30; j++) // getting random numbers for num1
{
num1[j] = 1 + rand() % (50 + 1 - 1);
printf("%d ", num1[j]);
}
printf("\nThis is num2:\n");
for (j = 0; j < 21; j++) // copying num1 array into num2 array, and only taking the first 21 numbers
{
num2[j] = num1[j];
printf("%d ", num2[j]);
if (x % 7 == 0) // this will print num2 with 3 rows each with 7 values
{
printf("\n");
}
x++;
}
最佳答案
我认为您已经完成了比最初提出的问题更多的事情。
In function main declare an integer array called
num1
with 30 elements and declare a second integer array callednum2
with 21 elements. To each element ofnum1
assign a random number between 1 and 50; print the numbers.
你已经做到了。请注意,对于如何初始化和打印数字没有限制。您可以使用 for
或 while
循环,或者只执行相同的操作 30 次。
In a
for
loop, copy the first 21 numbers fromnum1
tonum2
.
完成。不过,请参阅下面我的注释。
In another
for
loop print the element values fromnum2
, seven values per line. Find an algorithm that will print them from one loop, not 3 loops. (emphasis mine)
完成。您已经在一个循环中打印了这些值。 请注意,您已经超出了(我阅读的)原始问题所需的范围;您已将复制和打印操作合并到同一个循环中。我唯一关心的是为什么这个问题提到 3 个循环。我希望答案的简单实现是使用两个嵌套循环来打印值。因此,该问题的措辞可能含糊不清,并且您将复制和打印操作结合起来是正确的。我当然不认为您还需要做任何事情。
关于C - 将 2 for 循环重写为 1 for 循环以复制数组。,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53124744/