2011-02-13 100 views
3
//Page 215, #2, by Jeremy Mill 
//program taken in 7 values, displays them, and then sorts them from highest to  lowest, and displays them in order. 

#include <iostream> 
#include <iomanip> 

using namespace std; 

int main() 
{ 
//Define the variable we will need 
const int arraySize = 6; 
double dailySales[arraySize]; 

//Now let's prompt the user for their input 
for (int a=0 ; a <= arraySize; a++) 
    { 
    cout << "Please enter sale number " << a+1 << " :"; 
    cin >> dailySales[a]; 
    } 

//Now we display the output of the array 
cout << "\n\nSale Number" << setw(13) << "Value" << endl; 
    for (int i =0; i <= arraySize; i++)   
     cout << setw(5) << i << setw(14) << dailySales[ i ] << endl; 

//Now we sort using a bubble sort 
for(int b = 0; b<=arraySize; b++) 
     for(int c = arraySize-1; c>=b; c--) { 
      if(dailySales[c-1] > dailySales[c]) { // if out of order 
      // exchange elements 
      int t = 0;   
      t = dailySales[c-1]; 
       dailySales[c-1] = dailySales[c]; 
       dailySales[c] = t; 
      cout << "it ran"; 
      } 
     } 

cout << "Now we can display the array again! \n\n\n" << endl << dailySales[6] << endl; 

//Now we display the output of the sorted array 
cout << "\n\nSale Number" << setw(13) << "Value" << endl; 
    for (int d = 0; d <= arraySize; d++)   
     cout << setw(5) << d << setw(14) << dailySales[ d ] << endl; 

cin.clear(); //clear cin 
cin.sync(); //reinitialize it 
cout << "\n\nPress Enter to end the program\n\n"; //display this text 
cin.get(); //pause and wait for an enter 
return 0; 

} // end main 

輸出:C++意想不到陣列輸出

Please enter sale number 1 :1 
Please enter sale number 2 :2 
Please enter sale number 3 :3 
Please enter sale number 4 :4 
Please enter sale number 5 :5 
Please enter sale number 6 :6 
Please enter sale number 7 :7 


Sale Number  Value 
    0    1 
    1    2 
    2    3 
    3    4 
    4    5 
    5    6 
    6    7 
Now we can display the array again! 



7 


Sale Number  Value 
    0    1 
    1    2 
    2    3 
    3    4 
    4    5 
    5    6 
    6 2.97079e-313 


Press Enter to end the program 

爲什麼是它的最後一個 '值' 不是7,但在SCI該號碼。符號??

回答

7

在循環訪問數組時循環起來。環路必須從大小爲1的至 因此,而不是使用低於或相等:

for (int a = 0; a <= arraySize; a++) 

你應該使用低於:

for (int a = 0; a < arraySize; a++) 
+1

擊敗我一秒! +1給你,先生。另外,你能否在答案中告訴他爲什麼緩衝區超限是危險的。 – wheaties 2011-02-13 22:58:44

3

數組大小聲明爲6個元素,然後放置7個元素[0 ... 6]。

重新聲明數組大小爲7,然後在循環中將所有< =更改爲<。

+0

啊哈,謝謝你,我的想法不正確(數組大小是總數的元素,而不是最終元素的數量) – Jeremy 2011-02-13 23:03:03