C++ 意外的数组输出

标签 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

为什么最后一个'value'不是7,而是sci中的那个数字。符号??

最佳答案

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

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

你应该使用小于:

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

关于C++ 意外的数组输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4987477/

相关文章:

android - C++ 中对构造函数的 undefined reference

声明结构时的 C++ 问题

C++ 无法从 vector 访问对象

javascript - 为什么我的代码在每个元素后面返回一个逗号?

JAVA矩阵程序只打印0并且不接受输入

c - 初始化指向结构中二维数组的指针

数组的 C++ 模板并知道它们的大小

.Net ComboBox 绑定(bind)问题

algorithm - 如果我们使用链表实现桶,桶排序的复杂度是 O(n+k) 是多少?

ios - 将 SortInPlace 与一些可选值一起使用(无)