在动态数组C++中查找中间数

Finding middle number in dynamic array C++

本文关键字:查找 中间 C++ 动态 数组      更新时间:2023-10-16

我正试图在我的动态数组中找到中间数。用户输入三个数字,然后程序将其从最小到最大进行排序。它运行良好,直到我输入数字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;

一般来说,您可以从<algorithm>使用std::sort,尽管它会修改您的数组(如果您想保留原始输入,请制作一个副本)。

#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

下面块中的逻辑存在缺陷

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];
    }

}

因为smallmedhigh不是按顺序开始的。您可以使用std::sort,正如@kmac的回答中所建议的那样。如果你想自己编码,试试:

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];
   }
}

问题是当您检查"mid"时出现的第三种if情况,这永远不会是真的,因为您假设high是30,但此时您还没有检查number[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];
  }
}