c – 如何在保持其顺序的同时填充一组int?
作者:互联网
我正在尝试做一个简单的练习,我希望从用户输入填充一组int,并保持输入顺序,这样就不需要在用户完成后对数组进行排序.
假设数组的状态是这样的:{3,5,7,8,9, – , – , – , – , – }( – 表示空)
现在处于这种状态,例如,如果你输入6,arr [1]之后的所有元素都应该向前移动一个位置,这样6可以放在arr [2]中.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
bool ok = true;
int x // the input
, n = 0 // to keep track of numbers already in the array
, i, j // to iterate in loops
, arr[10];
cout << "Enter 10 numbers: \n";
while (cin >> x) {
if (n == 0) { arr[n] = x; n++; } // for the first entry.
else if (x < arr[0]) { // is x lower than the first element in the array?
for (i = n; i > 0; i--)
arr[i] = arr[i - 1];
arr[0] = x; n++;
}
else if (x > arr[n - 1]) { // is x greater than the top of already addded
// elements to the array?
arr[n] = x; n++;
}
else { // when x is in between of elements. Also I think the problem is here.
for (i = 0; i < n && ok; i++)
if (x > arr[i] && x < arr[i + 1]) {
for (j = n; j > i + 1; j--)
arr[j] = arr[j - 1];
ok = false;
}
arr[i + 1] = x; n++;
}
if (n == 10) break; // if you reached to end of the array, break while.
}
for (i = 0; i < 10; i++)
cout << arr[i] << " ";
cin.get();
cin.get();
}
这个代码有很多问题,但是当我尝试输入时:1,10,2,3,4,5,6,7,8,9,程序不会将10移动到数组的末尾,它输出:1,10,2,3,4,5,6,7,8,9.
解决方法:
这里的问题是,当前一个执行条件为真时,总是执行for循环的递增步骤.
for (i = 0; i < n && ok; i++) // i is incremented
if (x > arr[i] && x < arr[i + 1]) {
for (j = n; j > i + 1; j--)
arr[j] = arr[j - 1];
ok = false;
}
arr[i + 1] = x; n++;
因此在插入“2”后,for循环的条件为真:
for (i = 0; i < n && ok; i++)
然后执行for循环的主体并且i递增.
现在再次检查条件并将其评估为false,但不过我是1而不是预期值0.
表演后
arr[i + 1] = x; n++;
你的数组看起来像:
[1] [10] [2]
标签:c,arrays,sorting,console-application 来源: https://codeday.me/bug/20190829/1760780.html