我是C++的初学者,我有一个偶然发现的家庭作业。我必须找到最大和第二大的数**,不使用数组或向量**,只使用if或while语句。如果有人告诉我如何做,我会非常高兴。:)
这是我的程序到目前为止(我设法找到最大和最小)
`
std::cout << "Insert five numbers: " << std::endl;
int num1{};
int num2{};
int num3{};
int num4{};
int num5{};
std::cin >> num1 >> num2 >> num3 >> num4 >> num5;
std::cout << '\n';
// Find the largest number :
if ((num1 > num2) && (num1 > num3) && (num1 > num4) && (num1 > num5))
{
std::cout << "Number One " << "(" << (num1)<< ")" << " is the largest number !" << std::endl;
}
if ((num2 > num1) && (num2 > num3) && (num2 > num4) && (num2 > num5))
{
std::cout << "Number Two " << "(" << (num2) << ")" << "is the largest number !" << std::endl;
}
if ((num3 > num1) && (num3 > num2) && (num3 > num4) && (num3 > num5))
{
std::cout << "Number Three" << "(" << (num3) << ")" << " is the largest number !" << std::endl;
}
if ((num4 > num1) && (num4 > num2) && (num4 > num3) && (num4 > num5))
{
std::cout << "Number Four" << "(" << (num4) << ")" << " is the largest number !" << std::endl;
}
if ((num5 > num1) && (num5 > num2) && (num5 > num3) && (num5 > num4))
{
std::cout << "Number Five" << "(" << (num5) << ")" << " is the largest number !" << std::endl;
}
//Find the smallest number :
if ((num1 < num2) && (num1 < num3) && (num1 < num4) && (num1 < num5))
{
std::cout << "Number One" << "(" << (num1) << ")" << " is the smallest number !" << std::endl;
}
if ((num2 < num1) && (num2 < num3) && (num2 < num4) && (num2 < num5))
{
std::cout << "Number Two" << "(" << (num2) << ")" << " is the smallest number !" << std::endl;
}
if ((num3 < num1) && (num3 < num2) && (num3 < num4) && (num3 < num5))
{
std::cout << "Number Three" << "(" << (num3) << ")" << " is the smallest number !" << std::endl;
}
if ((num4 < num1) && (num4 < num2) && (num4 < num3) && (num4 < num5))
{
std::cout << "Number Four" << "(" << (num4) << ")" << " is the smallest number !" << std::endl;
}
if ((num5 < num1) && (num5 < num2) && (num5 < num3) && (num5 < num4))
{
std::cout << "Number Five" << "(" << (num5) << ")" << " is the smallest number !" << std::endl;
}
`
1条答案
按热度按时间uwopmtnx1#
你可以保持最大值和第二个最大值沿着你读你的输入数字。
我已经开始阅读循环外的第一个数字,并将
max_n
设置为它,因为它简化了循环内的代码。注意,
while (counter--)
会在循环开始时检查counter
,如果counter
为非零值,则进入循环,然后递减它。因此,在循环结束时,你将阅读counter
数字(4)。Demo(https://godbolt.org/z/9zr7rjv4a)
代码会发现第二大的数与最大的数不同。如果要让这两个数相同,就应该去掉
else if
中的n != max_n
比较。Demo(https://godbolt.org/z/ovbe5xhv5)