我正在嘗試在我的動態數組中找到中間數字。用戶輸入三個數字,然後程序將其從最小到最大排序。它工作正常,直到我輸入數字10,20,30它輸出10,10,30,當我輸入30,20,10輸出10,30,30。在動態數組中查找中間數字C++
這是我的代碼的一部分。 感謝
cout << "Enter 3 values and I will sort them from lowest to highest." << endl;
for (index = 0; index < 3; index++)
{
cin >> number[index];
while (cin.fail())//Check that values entered are the correct type.
{
cout << "You did not enter a number" << endl;
cout << "Enter a new number." << endl;
cin.clear();//Clears the input if user input non-integer value.
cin.ignore(1000, '\n');//Ignores up to 1000 characters or up to new line.
cin >> number[index];
}//end while
}//end for
cout << "You have entered the values" << endl;
for (index = 0; index < 3; index++)
{
cout << number[index] << " ";
cout << endl;
}//end for
small = number[0];
mid = number[0];
high = number[0];
for (int i = 0; i < 3; i++)//Goes through the array to determine order of values.
{
if (small > number[i])
{
small = number[i];
}
else if (high < number[i])
{
high = number[i];
}
else if (high > mid && mid > small)
{
mid = number[i];
}
}
cout << "Here is the new order of your numbers." << endl;
cout << small << endl;
cout << mid << endl;
cout << high << endl;
您需要向我們展示你如何申報數量 – 2014-09-30 03:40:43
您應該使用調試器來逐步執行代碼,找出原因如果輸出與您的期望有所不同。 – 2014-09-30 03:46:02
這個問題沒有顯示出太多的研究。用一張紙瀏覽你的循環,看看爲什麼每個變量都以它們的值爲結束。 – jxh 2014-09-30 04:02:36