![](/img/trans.png)
[英]I can't get my program to read the values from my input file correctly (2D array)
[英]Can't get my code to correctly sort user input array of numbers (using recursion)
為了我的一生,我無法使此代碼正確排序。 這是一種遞歸實踐,通過對用戶輸入的五個數字進行排序,然后顯示從最小到最大的五個數字。 它可以正確執行大多數操作,但偶爾會弄亂第一個或最后一個數字,並與數組中的另一個數字切換。 我知道問題出在哪里呢是在交換功能中,在第二個“如果”的聲明,但我無法弄清楚如何解決它,我真的很感激一些方向如何繼續。 這是我的代碼:
#include <iostream>
#include <array>
using namespace std;
void mySort(int nums[], int first, int size);
int main()
{
int fiveNumbers[5];
int firstNum = 0;
int size = 5;
cout << "Please enter five numbers, pressing enter after each.\n\n";
for (int i = 0; i < 5; i++)
{
cout << "Enter a number: ";
cin >> fiveNumbers[i];
cout << endl;
}
mySort(fiveNumbers, firstNum, size);
for (int i = 0; i < size; i++)
{
cout << fiveNumbers[i] << endl;
}
system("PAUSE");
return 0;
}
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (first < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
更改了我的函數,以反映數組AT點“第一”的值,而不是變量“第一”本身。 到目前為止,它每次都有效!
void mySort(int nums[], int first, int size)
{
if (size == 0)
{
return;
}
for (int i = 0; i < 5; i++)
{
if (nums[first] < nums[i])
{
swap(nums[first], nums[i]);
}
}
first++;
size--;
return mySort(nums, first, size);
}
編輯:使您的代碼工作,但忘記了最重要的部分,即:
您正在將索引與數組值進行比較,請使用:
if (nums[first] < nums[i])
代替:
if (first < nums[i])
此外,你總是從頭開始交換時,你應該開始一個過去的first
。
代替:
for (int i = 0; i < 5; i++)
你要:
for (int i = first + 1; i < 5; i++)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.