+ 1
[SOLVED] Find max from 3 numbers Using Function?
help me guys i wanna write a function to Find max number among 3 numbers https://code.sololearn.com/cDGHFW83XGP7/?ref=app
8 ответов
+ 1
You can use this:
int max(int x, int y, int z){
if(x>y){
if(x>z)
return x;
else
return z;
}
else{
if(y>z)
return y;
else
return z;
}
}
+ 2
#include <iostream>
using namespace std;
int max_of_three(int a, int b, int c)
{
int max_so_far = 0;
if (a > b)
{
max_so_far = a;
}
else
{
max_so_far = b;
}
if (c > max_so_far)
{
return c;
}
return max_so_far;
}
int main()
{
cout << max_of_three(1, 2, 3) << endl;
cout << max_of_three(1, 3, 2) << endl;
cout << max_of_three(2, 1, 3) << endl;
cout << max_of_three(2, 3, 1) << endl;
cout << max_of_three(3, 1, 2) << endl;
cout << max_of_three(3, 2, 1) << endl;
}
Result:
3
3
3
3
3
3
+ 2
Here is the answer with no IFs and Termary Operators.
template<typename T>
T max(T const&a,T const&b,T const&c)
{
return a*(a>=b&&a>=c)+b*(a<b&&b>=c)+c*(a<c&&b<c);
}
0
look into my code please
0
First version can only find max between 3 numbers, other takes an array which can be any size.
int max1(int a, int b, int c) {
int arr[3] = {a, b, c};
int maxNum = arr[0];
for (int i = 1; i < 3; i++) {
if (arr[i] > maxNum) maxNum = arr[i];
}
return maxNum;
}
int max2(int arr[]) {
int size = sizeof(arr) / sizeof(arr[0]);
int maxNum = arr[0];
for (int i = 1; i < size; i++) {
if (arr[i] > maxNum) maxNum = arr[i];
}
return maxNum;
}
0
you wrote parentheses with else()
are these necessary?
0
No, actually I did a mistake there, else doesn't have parentheses it would be
else{
/*your code*/
}
I've fixed this...
0
can we write like that in defining a function for max number
if (x>b && x>c)
{ return x;}
else if (b>a && b>c)
{ return b;}
else
return z;