在动态数组C++中查找中间数
Finding middle number in dynamic array C++
我正试图在我的动态数组中找到中间数。用户输入三个数字,然后程序将其从最小到最大进行排序。它运行良好,直到我输入数字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];
}
}
因为small
、med
和high
不是按顺序开始的。您可以使用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];
}
}
相关文章:
- 正在查找文档以获得PS4平台的C++中的设备信息
- 2D数组来自文本输入,中间有空格
- 在C++中查找文件
- 模板元程序查找相似的连续类型名称
- 在UNIX系统中使用DIR查找文件的字节大小
- 查找最接近的大于当前数字的数字的索引
- 有没有一种方法可以创建一个带有哈希表的数据库,该哈希表具有恒定时间查找功能
- 查找后更改类变量
- 使用正则表达式regex_search在字符串中查找字符串
- 使用gcc从静态链接的文件中查找可选符号
- 在C++中查找范围的长度
- 算法问题:查找从堆栈中弹出的所有序列
- 在Windows中查找扬声器输出的当前音量级别
- 查找中间两个数字的正则表达式的匹配项
- 在 c++ 中查找中间值
- 写入二进制文件的中间;使用tellg()查找长度
- std::multiset并查找中间元素
- C++ 使用函数模板查找任何输入数据类型的中间值
- 查找链表的中间节点
- 在动态数组C++中查找中间数