max函数与min函数(数的大小比较)

一、运用max函数来进行数的大小比较:

1.两个数

    float a;
	float b;
	cin >> a >> b;
	cout << max(a, b) << '\t'<< min(a, b) << endl;

#include<algorithm> //max,min的头文件

2.三个数

#include<iostream>
#include <algorithm>
using namespace std;
int main()
{
 int a, b, c; int x2, x1;
 cin >> a >> b >> c;
 x1 = max(a, b);  // 把 a,b 中大的值赋给 x1
 x2 = max(x1, c);  // 把 x1,c 中大的值赋给 x2
 cout << x2 << endl;  // 输出最大值
 return 0;
}

除了用上述方法外还可以用if语句

#include<iostream>
using namespace std;
int main()
{
    int a,b,c,t,e;
    cin>>a>>b>>c;
    if(a>b) t=a;
    else    t=b;
    if(t>c) e=t;
    else    e=c;
    cout<<e;
    return 0;
}

比较数还可以用三目运算符和宏

max=a>b ? a:b;

min=a<b ? a:b;

#define Max(a,b) (a>b ? a:b)

#define Min(a,b) (a<b ? a:b)

二、有一个较好的例子:

分别用函数和带参的宏,从三个数中找出最大的数。最大的数,输出两遍,先用函数,再用宏。 保留3位小数

#include<iostream>
#include<iomanip>
using namespace std;
float fun0(float a, float b, float c)
{
	float t = max(a, b);
	float data = max(t, c);
	return data;
}
#define fun(a,b,c) (a>b?(a>c?a:c):(b>c?b:c))
int main()
{
	float a,b,c;
	cin >> a>>b>>c;
	cout << fixed << setprecision(3)<< fun0(a, b, c) << endl;
	cout << fixed << setprecision(3) << fun(a, b, c);
	return 0;
}

运行结果:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

SweetCinderella

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值