Find the maximum value (three methods)

Example: Find the maximum value

Given three integers, please find the largest of them.

The following formula may help you:
max(a,b)=(a+b+abs(a−b))2
max(a,b)=(a+b+abs(a−b))2

Input format The
input occupies one line and contains three integers.

Output format The
output format is "X eh o maior", where X is the maximum of the three numbers.

Data range
1≤given integer≤1091≤given integer≤109
Input example:
7 14 106
Output example:
106 eh o maior

method one:

Direct if statement judgment

#include <iostream>
using namespace std;
int main()
{
    
    
    int a,b,c;
    cin>>a>>b>>c;
    int max;
    if(a>b&&a>c)
    max=a;
    if(c>a&&c>b)
    max=c;
    if(b>a&&b>c)
    max=b;
    cout<<max<<" eh o maior";
    return 0;
    
}

Method Two:

Use the formula given in the title

#include <iostream>
#include <cmath>
using namespace std;
int main()
{
    
    
    int a,b,c,max;
    cin>>a>>b>>c;
    max=(a+b+abs(a-b))/2;
    max=(max+c+abs(max-c))/2;
    cout<<max<<" eh o maior";
    return 0;
}

Here's why this formula can find the maximum value of two numbers:

当a>=b时,max(a,b)=(a+b+a-b)/2=a;
当a<b时,max(a,b)=(a+b+b-a)/2=b;

In fact, there is also a formula for finding the minimum of two numbers:

min(a,b)=(a+b-abs(a-b))/2;

Method three:

Use C++ to specifically find the maximum and minimum values ​​of two numbers, that is, max() in the algorithm header file

#include <iostream>
#include <algorithm>///一定要写这个头文件
using namespace std;
int main(){
    
    
    int a,b,c;
    int max1 = 0;
    cin>>a>>b>>c;
    max1 = max(a,b);///调用库函数max
    max1 = max(max1,c);
    cout<<max1<<" eh o maior"<<endl;
    return 0;
}

Note:
① Some people say that max() and min() can be run without the algorithm header file, which is only for individual compilers.
②Some people on the Internet say that when doing online programming questions on Niuke.com, there is a problem that uses the max function and found a small pit. For example, when max(a,0), if a is a long long type, an error will be reported and you need to change 0 is changed to 0ll.

Guess you like

Origin blog.csdn.net/qq_46009744/article/details/108583055