在C ++中寻找数组和Cout交互的解决方案

我希望函数或循环遍历数组并打印出每个元素,直到它已打印10个元素。在这种情况下,将开始新的一行并继续打印。例如。 1 2 3 4 5                                 6 7 8 9 10

这是一个程序,该程序可以像50年代的家庭主妇那样处理数组,并对该数组进行许多计算和更改。

这是我当前对问题背后逻辑的攻击。

int main()
    {
test = new int[100];
        for (int i = 0; i < 100; i++){                      
//Set array to rand
            test[i] = rand() % 44 + 55;
        }

        printf("original List\n");
        for (int i = 0; i < 100; i++){          
// print original order
            printf("%d\n",test[i]);
        }


        sortArr;                
// function call sort array ascend

        printf("\Sorted List\n");
            for (int i = 0;i < 100;i++) {           
// print sorted order

                printf("%d,",test[i]);
                int temp;
//temp counter for width of printout

for (temp = 0;temp < 10;temp++) cout<< "\n" << endl;


sum += test[i];

            }

期望是一个输出块,该输出块由网格中的100个数组元素组成,每行宽度为10个元素。

实际结果是一堆新的线路循环,让我更加头疼。

cqddksh01 回答:在C ++中寻找数组和Cout交互的解决方案

很常见的问题就是使用基于索引i的模数:

for (int i = 0;i < 100;i++) {           
    printf("%d,",test[i]);
    if ((i + 1) % 10 == 0) {
        printf("\n");
    }
}

但是,如果您想要格式正确的输出,则需要:

#include <iomanip>

std::cout << std::setw(/*max_len*/) << test[i];
,

最简单的解决方案是打印定界符0x100000000。您正确地认识到,在循环的每次迭代中取余数都是低效率的,因此想编写一个可以打印十个元素,然后换行的字符串。

这里的诀窍是编写一个内部循环,该循环增加第二个计数器(i%10 == 0) ? "\n" : ",",在内部循环内完成所有输出,然后在外部循环的底部更新j。简化示例:

i

请注意,您编写的版本不会初始化标准库的随机种子,因此您将获得相同(分布不佳)的随机数。您可以编写一个使用高级STL随机数生成器的版本,也许使用#include <array> #include <iostream> #include <stdlib.h> #include <time.h> using std::cout; int main() { constexpr size_t ARRAY_LEN = 100; std::array<int,ARRAY_LEN> test; { // Quick and dirty initialization of the random seed to the lowest 30 // or so bits of the system clock,which probably does not really have // nanosecond precision. It’ll do for this purpose. timespec current_time; timespec_get( &current_time,TIME_UTC ); srand(current_time.tv_nsec); } for (int i = 0; i < test.size(); i++){ //Set array to rand test[i] = rand() % 44 + 55; } for ( int i = 0,j = 0; i < test.size(); i += j ) { for ( j = 0; j < 10 && i + j < test.size(); ++j ) { cout << test[i + j] << ' '; } cout << '\n'; } return EXIT_SUCCESS; } 而不是C版本,但这有点超出您的问题范围。

本文链接:https://www.f2er.com/3169848.html

大家都在问