【问题标题】:Looking for solution to array and cout interaction in C++寻找 C++ 中数组和 cout 交互的解决方案
【发布时间】:2019-11-03 22:52:11
【问题描述】:

我想要一个函数或循环遍历数组并打印出每个元素,直到它打印出 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 个元素。

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

【问题讨论】:

  • 嗯,你对运行十次的for 循环有什么期望,每次循环打印一个换行符,然后是另一个换行符(来自std::endl)?如果您预期的不是连续的 20 个换行符,您能解释一下为什么您预期的不是这个非常简单的 for 循环的简单结果吗?你想要的只是每 10 个元素后一个换行符。您碰巧已经在使用 i 来计算每个元素,因为它被打印出来,所以只需每十个 is 添加一个换行符。
  • @SamVarshavchik 请客气点?
  • 我预计在 for 循环 10 次计数后会出现换行符,但似乎理解您所说的换行符因此呈指数增长的问题。
  • 您正在打印一个换行符,然后是 std::endl 在一个不执行任何其他操作的循环中。当然,最终结果将是连续 20 个换行符。

标签: c++ arrays for-loop cout


【解决方案1】:

很常见的问题只是使用基于索引 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];

【讨论】:

  • 非常感谢。我必须记住带有模数索引的 if 语句。超级有用!
【解决方案2】:

最简单的解决方案是打印分隔符(i%10 == 0) ? "\n" : ", "。您正确地认识到在循环的每次迭代中取余数是低效的,并想编写一个打印十个元素后跟一个换行符的程序。

其中的诀窍是编写一个内部循环,增加第二个计数器j,在内循环内完成所有输出,然后在外循环底部更新i。一个简化的例子:

#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;
}

请注意,您编写的版本不会初始化标准库的随机种子,因此您会得到相同(分布不均)的随机数。您可以编写一个使用更高级的 STL 随机数生成器和&lt;chrono&gt; 的版本,而不是 C 版本,但这有点超出您的问题范围。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-07-20
    • 2017-07-27
    • 1970-01-01
    • 2019-01-16
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多