C++:数字排列程序无法正常工作

标签 c++

我尝试编写一个程序来对数组的数字进行排序。

我已经尽力了,但是有一个问题:虽然我做了一个循环来交换数字并排列它们,但是当我输出数组时,没有任何变化,数组保持不变。

代码会让一切变得更清晰

这是主要功能:

int main(){
int arr[10];
//For loop to get from user numbers to be put into the array
for ( int i = 0; i<10; i++){
    cout << "Enter the number to be recorded: ";
    cin >> arr[i];
    cout << endl;
}
// Set counter n to 0 ( counts numbes of number swaps)
int n = 0;
do {
    //re sets counter to 0
    n=0;

    //Check the entire loop if arr[i] bigger than arr[i+1] and swaps their values if true then adds 1 to n
    for ( int i = 0; i>9; i++){
        if(arr[i]>arr[i+1]){
            swap(&arr[i], &arr[i+1]);//swaps by sending the addresses of the two array elements the pointers in the swap function
            n++;
        }
    }
}while(n>0); // if counter = 0 then end (therefore the numbers are arranged correctly since no swapping happened)
cout << "The numbers ordered are:\n\n";
// Loop to output the arranged array
for (int i =0; i<10; i++){
    cout << arr[i] << ", ";
}
cout<<endl;
system("PAUSE");
return 0;}

这是交换函数:

void swap ( int *p, int *t){
int temp;
temp = *p;
*p = *t;
*t = temp;}

我希望你们能帮我解决我的问题,并告诉我这段代码有什么问题

谢谢大家

最佳答案

仔细观察你的 for 循环......它的内容永远不会被执行。

for ( int i = 0; i>9; i++){ ... }

条件i>9应该是 i<9 .

关于C++:数字排列程序无法正常工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11697848/

相关文章:

c++ - 如何将字符串插入到sql查询中?

c++ - qi % 运算符使用 (1) 分隔符属性和 (2) 接受尾随分隔符

C++ 用非静态函数重载静态函数

C++ header 保持理智

c++ - 利用计时器更新 MFC 文档/ View 应用程序

c++ - 如何检查传递给 Lua 的参数是否是用户定义的类型?

c++ - Qt QPainter 以毫米而不是英寸为单位

c++ - 是否有任何快速技术来获取子网中的所有 ip 地址?

c++ - Boost asio 自定义 HTTP 服务器读取 HTTP post 请求

float 和字节数组问题的 C++ union