min() max() - երկու արժեքների միջև

Երկու արժեքների մեջ մեծագույնը վերցնելու համար կարելի է օգտագործել if, բայց կարելի է նաև օգտագործել max ֆունկցիան <algorithm> գրադարանի մեջից։
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
	int a = 100;
	int b = 77;
	cout << a << " " << b << endl;

	int big;
	if (a > b)
		big = a;
	else
		big = b;

	cout << big;
	return 0;
}
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
  int a = 100;
  int b = 77;
  cout << a << " " << b << endl;

  int big = max(a, b);
  cout << big;
  return 0;
}
Երկու դեպքում էլ ծրագիրը նույն կերպ է աշխատում՝
100 77
100
min() և max() ֆունկցիաները կարելի է օգտագործել ոչ միայն int փոփոխականների հետ, այլ նաև բոլոր հնարավոր տիպերի հետ, որոնք հնարավոր է իրար հետ համեմատել (այսինքն փոփոխականները կարելի է համեմատել մեծի կամ փոքրի նշանի միջոցով)։
 
Շատ հարմար է այս ֆունկցիաներն օգտագործել ցիկլերի մեջ առանց if/else լավագույն արժեքներ գտնելու համար՝
#include <iostream>
#include <algorithm>
using namespace std;

int main() {
	double price[100];
	for (int i=0; i < 100; ++i)
		cin >> price[i];

	double bestPrice = a[0];
	for (int i=1; i < 100; ++i)
		bestPrice = min(bestPrice, price[i]);

	cout << "The cheapest option is: " << bestPrice;
	return 0;
}
 
Վարժություն՝
Տրված է 4 թիվ՝ a b c d։ Անհրաժեշտ է հաշվել առաջին զույգի և երկրորդ զույգի մեծագույններից փոքրագույնը։ Այսինքն a և b-ի մեծագույնը այնուհետև c և d-ի մեծագույնը և ապա դրանց փոքրագույնը։
Մուտք
Ելք
2 4 3 8
4
 

Constraints

Time limit: 0.2 seconds

Memory limit: 512 MB

Output limit: 1 MB

To check your solution you need to sign in
Sign in to continue