三个数字之间的 C++ 相加两个更高的数字,没有循环和数组



如何编写允许用户输入三个数字的C ++程序,并在这三个数字之间找到2 higest并写成:5,3,4 5 和 4 的总和是 9!

我尝试了一切准备就绪,但是我得到了太多,如果不是的话,它看起来真的很糟糕,甚至在所有情况下都不能很好地工作:/

#include <iostream>
#include<math.h>
using namespace std;
int main()
{
float n1, n2, n3;
cout << "Enter three numbers: ";
cin >> n1 >> n2 >> n3;
if(n1 >= n2 && n1 >= n3)
{
if(n2>=n1 && n2>=3)
cout << "Sum of 2 highest between this three numbers is: "  << cout<<n1+n2;
}
if(n1 >= n2 && n1 >= n3)
{
if(n3>=n1 && n3>=n2)
cout << "Sum of 2 highest between this three numbers is: "  << cout<<n1+n3;
}
if(n2 >= n1 && n2 >= n3)
{
if(n3 >= n1 && n3 >= n2) {
cout << "Sum of 2 highest between this three numbers is: " << cout<<n3+n2;
}
}
if(n3 >= n1 && n3 >= n2)
{
if(n2 >= n1) {
cout << "Sum of 2 highest between this three numbers is: "  << cout<<n3+n2;
}
}
if(n3 >= n1 && n3 >= n2)
{
if(n1>= n2) {
cout << "Sum of 2 highest between this three numbers is: "  << cout<<n3+n1;
}
}
return 0;
}

先找到最小值,

double min = std::min(n1, std:min(n2, n3)); // or std::min({n1, n2, n3})

然后消除它

if(min == n1)
{ 
std::cout << n2 << ' ' << n3 << ' ' << n2 + n3;
}
else if(min == n2) 
{ 
std::cout << n1 << ' ' << n3 << ' ' << n1 + n3;
}
else 
{ 
std::cout << n1 << ' ' << n2 << ' ' << n1 + n2;
}

现场示例

当然,如果你真的很挑剔,你可以代替std::min的电话

double min = n1;
if(n2 < min)
min = n2;
if(n3 < min)
min = n3;

另一种解决方案是在一个步骤中完成最小查找和消除,例如

if(n1 < n2 && n1 < n3) // min is n1
{
std::cout << n2 << ' ' << n3 << ' ' << n2 + n3;
}
else if(n2 < n1 && n2 < n3) // min is n2
{
std::cout << n1 << ' ' << n3 << ' ' << n1 + n3;
}
else // min is n3
{
std::cout << n1 << ' ' << n2 << ' ' << n1 + n2;
}

就复杂性而言,两种解决方案是相同的,即需要 4 次比较。

试试这个:

max = (n1>n2) ? ( (n1>n3) ? n1 : n3) : ((n2>n3) ? n2 : n3);
second = (n1==max) ? ( (n2>n3) ? n2 : n3) : ((n2==max) ? ((n1>n3) ? n1 : n3) : ((n2>n1)? n2 : n1));

您只需要做一些检查即可获得所需的结果。

int n1 = 0,n2 = 0,n3 = 0;
cin>>n1>>n2>>n3;
int highest = 0;
int second_highest = 0;
if(n1 > n2)
{
if(n1 > n3)
{
highest = n1;
if(n3 > n2)
{
second_highest = n3;
}
else
{
second_highest = n2;
}
}
else
{
highest = n3;
second_highest = n1;
}
}
else if(n2 > n3) // if the first if is false it means that the n2 is highest or second highest
{
highest = n2;
if(n1 > n3)
{
second_highest = n1;
}
else
{
second_highest = n3;
}
}
else
{
highest = n3;
second_highest = n2;
}
cout << "Highest: " << highest << "nSecond highest: " << second_highest;

希望有帮助。

回答所问问题的一种简单方法是

cout << "Sum of 2 highest between this three numbers is: ";
cout << (long long) n1 + n2 + n3 - std::min(n1, std::min(n2, n3));

或 (C++11)

cout << "Sum of 2 highest between this three numbers is: ";
cout << (long long) n1 + n2 + n3 - std::min({n1, n2, n3});

(long long)转换强制在操作之前提升所有要添加或减去的值,以避免在int支持的值范围小于long long时溢出。

当然,这确实嵌入了三个值的固定假设。

最新更新