c++ - 初始化数组 C++

标签 c++ arrays initialization

我有以下格式打印时间的代码:00 01 02 03 04 05 06 07 08 09 10 11...只是第一个数字 (0) 需要高于第二个数字 (0)。 . 下面是我的

#include <iostream>

using namespace std;

void printArray (int arg[], int length) {
  for (int n=0; n<length; ++n)
    cout << arg[n] << ' ';
  cout << '\n';
}

int main() 
{
    int ftime[99] = {0,0,0,0,0,0,0,0,0,0,1,1,1,1,1,1,1,1,1,1,2};
    int ttime[99] = {0,1,2,3,4,5,6,7,8,9,0,1,2,3,4,5,6,7,8,9,0};

    cout << "Time: ";printArray(ftime,21);
    cout << "     ";printArray(ttime, 21);

    return 0;
}

现在打印出以下内容:

Time: 0 0 0 0 0 0 0 0 0 0 1 1 1 1 1 1 1 1 1 1 2
      0 1 2 3 4 5 6 7 8 9 0 1 2 3 4 5 6 7 8 9 0

这正是我想要的,但我需要一直这样做到 99,并且想知道是否有比我这样做更简单的方法来初始化 ftime 和 ttime 数组。任何输入将不胜感激!

最佳答案

只需给它一个循环即可。

#include <iostream>

using namespace std;

void printArray (int arg[], int length) {
  for (int n=0; n<length; ++n) {
      cout << arg[n] << ' ';
  }
  cout << '\n';
}

int main() 
{
    int ftime[100]; 
    int ttime[100]; 
    for (int i = 0; i < 100; i++) {
        ftime[i] = i / 10;
        ttime[i] = i % 10;
    }

    cout << "Time: "; 
    printArray(ftime,100);
    cout << "      "; 
    printArray(ttime,100);



    return 0;
}

关于c++ - 初始化数组 C++,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26660971/

相关文章:

c++ - 围绕 boost::ptree 头痛的模板化类

c++ - 为什么要调用复制构造函数来构造一个空的 unique_ptr vector ?

c++ - 按类型检索可变参数类的给定成员

java - 为什么即使提供了初始容量,我们也不能在将元素添加到第 (n-1) 个索引之前将元素添加到列表中的第 n 个索引

python - 计算数组列表的概率时出错

c++ - 如何确保 C++ 类模板中非静态数据成员的正确初始化

c++ - 使用 MPI 在多个内核上运行

javascript - 将数组更改为小写

javascript - 仅在 AngularJS 中完成初始化后才运行 Controller

swift - 便利初始化程序不断崩溃,但指定的初始化程序工作正常吗?