我正在尝试在动态数组中找到中间数字。用户输入三个数字,然后程序将其从最小到最大排序。它工作正常,直到我输入数字10,20,30它输出10,10,30当我输入30,20,10它输出10,30,30。
这是我的代码的一部分。 感谢
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;
答案 0 :(得分:1)
更一般地说,您可以使用std::sort
中的<algorithm>
,但它会修改您的数组(如果您想保留原始输入,请复制一份)。
#include <cstdio>
#include <algorithm>
int main()
{
int nums[] = {5, 1, 7};
unsigned int num_size = sizeof(nums)/sizeof(nums[0]);
std::sort(nums, nums+num_size);
std::cout << "Here is the order of your numbers:" << std::endl;
for (unsigned int i=0; i<num_size; ++i)
std::cout << nums[i] << std::endl;
return 0;
}
输出:
Here is the order of your numbers:
1
5
7
答案 1 :(得分:0)
以下街区中的逻辑存在缺陷
for (int i = 0; i < 3; i++)
{
if (small > number[i])
{
small = number[i];
}
else if (high < number[i])
{
high = number[i];
}
else if (high > mid && mid > small)
{
mid = number[i];
}
}
由于small
,med
和high
未被命令开始。您可以按照@kmac的回答中的建议使用std::sort
。如果您想自己编写代码,请尝试:
for (int i = 0; i < 3; i++)
{
if (small > number[i])
{
small = number[i];
}
if (high < number[i])
{
high = number[i];
}
}
for (int i = 0; i < 3; i++)
{
if ( number[i] > small && number[i] < high )
{
mid = number[i];
}
}
答案 2 :(得分:0)
当你检查'mid'时,问题是你的第三个if-case,这永远不会是真的,因为你认为高是30,但你还没有检查数字[2] =='30'。
而是写这样的东西
// first find max,min
for (int i = 0; i < 3; ++i)
{
if (number[i] < small)
{
small = number[i];
}
if (number[i] > high)
{
high = number[i];
}
}
// then find mid
for (int i = 0; i < 3; ++i)
{
if (number[i] > small && number[i] < high)
{
mid = number[i];
}
}