+ 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

15th Apr 2018, 6:34 PM
Mushtaq Khan
Mushtaq Khan - avatar
8 Antworten
+ 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; } }
15th Apr 2018, 8:26 PM
LoneStar420
LoneStar420 - avatar
+ 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
15th Apr 2018, 7:59 PM
Emma
+ 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); }
16th Apr 2018, 7:56 PM
刘宇轩,一个来自西安的喜欢取长昵称的大学生。
刘宇轩,一个来自西安的喜欢取长昵称的大学生。 - avatar
0
look into my code please
15th Apr 2018, 8:11 PM
Mushtaq Khan
Mushtaq Khan - avatar
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; }
15th Apr 2018, 8:26 PM
TurtleShell
TurtleShell - avatar
0
you wrote parentheses with else() are these necessary?
15th Apr 2018, 8:31 PM
Mushtaq Khan
Mushtaq Khan - avatar
0
No, actually I did a mistake there, else doesn't have parentheses it would be else{ /*your code*/ } I've fixed this...
15th Apr 2018, 8:35 PM
LoneStar420
LoneStar420 - avatar
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;
15th Apr 2018, 8:44 PM
Mushtaq Khan
Mushtaq Khan - avatar