c++ - 用 C++ 对数字进行排序

标签 c++

因此,我编写了对数字进行排序的程序,但每当我执行它时,它都会将最小的随机数添加为“已排序数字”行中的第一个。

代码如下:

#include "stdafx.h"
#include <stdlib.h>
#include <iostream>
#include <time.h>

using namespace std;

int main(){

    const int MAX_SIZE = 100;
    int numbers[MAX_SIZE];
    int numElements;

    cout << "=============================" << endl;
    cout << "Welcome to BubbleSort Program" << endl;
    cout << "=============================" << endl;
    cout << endl;

    cout << "How many random numbers do you want us to produce? ";
    cin >> numElements;
    cout << endl;


    srand(static_cast<unsigned int>(time(0)));

    cout << "=============================" << endl;
    cout << "Random numbers: " << endl;
    cout << "=============================" << endl;

    for(int i = 0; i < numElements; i++){

        numbers[i] = (rand()%100) + 1;
        cout << numbers[i] << endl;
        if(i == numElements){
            cout << "i";
        }
    }


    int exchanges;
    int temp;
    int j;

    cout << "=============================" << endl; 
    cout << "Sorted numbers: " << endl;
    cout << "=============================" << endl;

    for(int i = 0; i <= numElements; i++){
        for(int j = 0; j < numElements; j++){

            if(numbers[j] > numbers[j + 1]){

                temp = numbers[j];
                numbers[j] = numbers[j + 1];
                numbers[j + 1] = temp;

            }
        }
    }

    for(int i = 0; i <= numElements; i++) {
        cout << numbers[i] << endl;
    }

    cout << "=============================" << endl;
    return 0;
}

输出示例:

============================= Welcome to BubbleSort Program =============================

How many random numbers do you want us to produce? 3

=============================
Random numbers:
=============================
69
8
5
=============================
Sorted numbers:
=============================
-858993460
5
8
69
=============================
Press any key to continue . . .

WTF 是-858993460?!

最佳答案

您正在访问未初始化的内存 -

for(int i = 0; i <= numElements; i++) { // <-- no, stop at < -- see above.
  for(int j = 0; j < numElements; j++) // <-- you use j+1 below

应该是

for (int i = 0; i < numElements; i++) { // <-- also not initialized.
  for (int j = 0; j < numElements - 1; j++) // <-- like so.

关于c++ - 用 C++ 对数字进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20509564/

相关文章:

c++ - 如果在我的机器上 sizeof(long) == sizeof(long long),为什么它们不是同一类型?

c++ - 快板不适用于 clion (0xC000007B)

c++ getline 在 Windows 中读取整个文件

用于下载电子邮件的 C++ IMAP 库

c++ - 头文件导入行为异常

c++ - 如何解决 Boost::BGL 模板<->类循环依赖?

c++ - 为什么 Visual Studio 2012 不为我插入括号?

java - 通过编程语言访问 Skype

c++ - 最小实例化类对象,查询getInstance<T>()时,基于继承

c++ - 析构函数的奇怪行为