2014-10-30 98 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; 
}