gpt4 book ai didi

c++ - 如何每行打印特定数量的数组元素?

转载 作者:太空狗 更新时间:2023-10-29 23:21:35 25 4
gpt4 key购买 nike

我想在数组的每一行打印 10 个元素,所以输出看起来像这样:

 1  2  3  4  5  6  7  8  9 10
11 12 13 14 15 16 17 18 19 20
...etc

到目前为止,这是我的代码:

#include <iostream>
#include <ctime>
#include <cstdlib>
#include <algorithm>

using namespace std;

int main()
{
srand(time(0));
int array[1000];
for (int i = 0; i < 1000; i++) array[i] = rand() % 1000;
sort(array, array + 1000);
for (int i = 0; i < 1000;){
i += 10;
for(int j = 0; j < i; j++){
cout << array[j] << " ";
}
cout << endl;
}
return 0;
}

但我无法让它工作。出于某种原因,它一遍又一遍地重复所有数字。

最佳答案

内部循环只使用参数列表中的j。它还需要考虑 i 以便它可以跳过已经打印出的数字

不过还有一个更简单的方法。不用嵌套循环,只需每 10 个元素打印出一行。

for (int i = 0; i < 1000;) {
cout << array[i] << " ";
if ((i + 1) % 10 == 0) {
cout << endl;
}
}

关于c++ - 如何每行打印特定数量的数组元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21009569/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com