在找到随机数量的第二个最小的输入时,我一直在尝试修复代码问题。 每当我在每个之后输入两个或多个相同值的数字并且后跟不同的更高数字(例如:1 1 3 4)(例如:3 3 3 4 5)时,即使不是这样,我总是会得到错误我想要程序做什么。 任何线索都会非常感激。 谢谢!
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main ()
{
double smallest, second_Smallest,a;
vector<double> v(0);
cout << "Enter the numbers in random order: " << endl;
try
{
while (cin >> a)
{
v.push_back(a);
}
if(v[0] < v[1])
{
smallest = v[0];
second_Smallest = v[1];
}
else
{
smallest = v[1];
second_Smallest = v[0];
}
for(int i = 2; i < v.size(); i++)
{
if (smallest > v[i])
{
second_Smallest = smallest;
smallest = v[i];
}
else if (v[i] < second_Smallest)
{
second_Smallest = v[i];
}
}
if (smallest == second_Smallest)
{
throw runtime_error("no second smallest");
}
else
{
cout << "The second smallest number is " << second_Smallest << endl;
}
}
catch (runtime_error)
{
cout << "error: no second smallest " << endl;
}
return 0;
}
答案 0 :(得分:0)
这是因为您的代码设置最小和第二小到相同的值,如果前两个数字相等而其他所有数字都更高,则永远不会重置它。实际上你不需要两个特殊条件。
试试这个:
#include <iostream>
#include <vector>
#include <stdexcept>
using namespace std;
int main ()
{
double smallest = 0xffff, second_Smallest=0xffff ,a;
vector<double> v(0);
cout << "Enter the numbers in random order: " << endl;
try
{
while (cin >> a)
{
v.push_back(a);
}
for(int i = 0; i < v.size(); i++)
{
if (smallest > v[i])
{
second_Smallest = smallest;
smallest = v[i];
}
else if (v[i] < second_Smallest)
{
second_Smallest = v[i];
}
}
if (0xffff == second_Smallest)
{
throw runtime_error("no second smallest");
}
else
{
cout << "The second smallest number is " << second_Smallest << endl;
}
}
catch (runtime_error)
{
cout << "error: no second smallest " << endl;
}
return 0;
}