2017-07-07 32 views
0

下面的代碼:在下面的代碼中,爲什麼不在輸出中顯示數組的值?

#include<iostream> 
using namespace std; 


int main() 
{ 
    int n, counter = 0; 
    cout << "how many markers do you have? "; 
    cin >> n; 
    int* Arr = new int[n]; //markers 
    int* cnt = new int[n]; 


    cout << "enter your marker color numbers here" << endl << " choose between 1 to 100: " << endl; 
    for (int j = 0; j < n; j++) 
     cin >> Arr[j]; 


    for (int i = 0; i < n; i++) 
{  for (int j = 1; j <= 100; j++) 
      if (Arr[i] == j) 
      { 
       counter = j; 
       cnt[counter--] = counter + cnt[counter--]; 
      } 
      else 
      { 
       j++; 
      } 
} 

    for (int f = 0; f < n; f++) 
     cout <<endl<<endl<<endl<<"here is the cnt "<<f<<": "<<cnt[f]<<"  "; 

    return 0; 
} 

,並在輸出CNT的替代細胞的價值觀,我得到的垃圾值。 我希望它將計數器添加到cnet數組的值。

+2

你怎麼能不知道你正在編程的編程語言? – Lundin

+0

你有沒有調試你的程序? –

回答

0

cnt[counter--] = counter + cnt[counter--]; 

的用法是錯誤的,那就是,你正在試圖指的是碳納米管陣列不與分配的指數。 因爲cnt數組聲明的大小爲n。 Cnt數組獲取從0到n-1的分配。 let let if if n == 3,Your cnt array will have the storage space from cnt [0] to cnt [n-1]。 在你的第二個for循環中,如果counter == 8,那麼cnt [8]沒有被分配,它只是拋出一些垃圾值,希望你明白。

+0

即將發佈類似於此的答案。 –

+0

我必須補充的一點是,counter--是一個操作,因此會影響整個變量並更改變量值,而不是操作它所代表的值。 –

+1

而且計數器變量也會在那一行中遞減兩次,我不這麼認爲,不需要兩次去計數器變量。 – Goutham

相關問題