C ++意外的数组输出

时间:2011-02-13 22:52:42

标签: c++ arrays sorting

//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

输出:

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中的那个数字。符号??

2 个答案:

答案 0 :(得分:7)

循环播放数组时要小心。循环必须从 0 开始到 size-1。 所以不要使用小于或等于:

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

你应该使用少于:

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

答案 1 :(得分:3)

数组大小声明为6个元素,然后将7个元素[0 ... 6]放入其中。

将数组大小重新设置为7,然后将所有&lt; =更改为&lt;在循环中。