2014-10-30 90 views
0

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

#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数组,而不是以我所做的方式。任何投入将不胜感激!

+0

_“如果有初始化一个更简单的方法既” _取决于数量的方案你需要存储在数组中。 – 2014-10-30 18:47:58

+0

你可以使用循环来提供数据 – 2014-10-30 18:48:05

+0

你不能只是循环来创建数组吗?我们实际上不确定为什么在声明期间尝试初始化数组时,为自己创建了限制 – Titus 2014-10-30 18:50:10

回答

1

简单的循环会做到这一点。

int j = -1; 
for(unsigned int i = 0; i < 99; ++i) { 
    ttime[i] = i % 10; 
    if(i % 10 == 0) { 
     ++j; 
    } 
    ftime[i] = j; 
} 
0

这样的事情?

int ftime[99]; 
int i; 
for (i=0; i < 99; i++) { 
    if (i/2 == 1) 
    ftime[i] = 1; 
    else if (i==20) 
    ftime[i] = 2; 
    else 
    ftime[i] = 0;  
} 
for (i=0; i < 99; i++) { 
    if (i/2 < 2) 
    ttime[i] = i % 10; 
    else 
    ttime[i] = 0;  
} 
2

只要喂它一个循环。

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

这个最初的ftime是9而不是0 ..所以它开始为09 01 02 03 .. – 2014-10-30 19:11:45

+0

@FreddyRivas它当然不会...... – Barry 2014-10-30 19:40:13

0
#define MAX 99 

int ftime [MAX+1]; // Includes 00 too 
int ttime [MAX+1]; // Includes 00 too 

for (int ctr = 0; ctr < MAX+1, ctr++) { 
    ftime[ctr] = floor(ctr/10); 
    ttime[ctr] = ctr % 10; // modulus oper 
} 

这可能有语法错误,对不起。我的这台电脑上没有c-compiler。

0

你可以做一个双层的,statment 例如:

int k = 0; 
for(int i = 0; i < 9, i++){ 
     for(int j = 0; j < 9, j++){ 
      ftime[k] = i; 
      ttime[k] = j; 
      k++; 
     } 
} 

记住K.I.S.S.

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]; 
    int ttime[99]; 

    for(int j=0; j < 99; j++) 
    { 

     ftime[j] = j/10; 
     ttime[j] = j%10; 
    } 
    cout << "Time: ";printArray(ftime,99); 
    cout << "  ";printArray(ttime, 99); 

    return 0; 
} 
0

声明既作为整数和使用循环以下

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