This is a discussion on simple programme to find the largest of three within the C++ Programming forums, part of the General Programming Boards category; Originally Posted by C_ntua The logic is not correct, the reverse is correct. The rule is when you have integers ...
I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.
Hi
I need your advice and opinion. So please help me. In the CODE 1 the largest of three numbers is found and the second CODE 2 also involves the same problem except that now we have four numbers. Don't you think the logic used in CODE 2 more simple and understandable? Any advice. I'm grateful for your guidance and time. (Sorry, if there is problem with the indentation)
CODE 1:
Code:// program to find the largest of three numbers; assuming all the numbers are distinct #include <iostream> #include <conio.h> using namespace std; int main() { float a, b, c; cout << "Enter the three numbers" << endl; cout << "Enter a = "; cin >> a; cout << "Enter b = "; cin >> b; cout << "Enter c = "; cin >> c; if ( (a > b)&&(b > c) ) cout << "a is the largest" << endl; else if ( (c > b)&&( a > c) ) cout << "a is the largest" << endl; else if ( (b > a)&&( b > c) ) cout << "b is the largest" << endl; else if ( (c > a)&&( c > b) ) cout << "c is the largest" << endl; getch(); }
CODE 2:
Code:// program to find the largest of four numbers; assuming all the numbers are distinct #include <iostream> #include <cstdlib> #include <windows.h> using namespace std; int main() { system("cls"); float a, b, c, d; cout << "Enter the numbers below" << endl; cout << "a = "; cin >> a; cout << "b = "; cin >> b; cout << "c = "; cin >> c; cout << "d = "; cin >> d; { if ( (a > b) && (a > c) && (a > d) ) cout << "a is the largest" << endl; else if ( (b > c) && (b > d) ) /* no need to check against "a" */ cout << "b is the largest" << endl; else if ( (c > d) ) cout << "c is the largest" << endl; else if ( (d > c) ) cout << "d is the largest" << endl; else cout << "Input error" << endl; } system("pause"); }
I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.
I'm sorry if this is to be considered premature bumping but I need your advice or opinion on the previous a little urgently, so please help me. Thanks.
I'm an outright beginner. Using Win XP Pro and Code::Blocks. Be nice to me, please.
It looks to me that for code 2 if you have a = 1, b = 2, c = 3, d = 3, then you'll get "Input error". You may indeed consider this an error if you wanted all the numbers to be different, but then if you enter a = 3, b = 3, c = 2, d = 1, it will simply say "b is the largest".
In terms of which logic is more understandable, it seems code 2 is really just an optimised version of code 1 so code 2 would probably be better if it weren't for the caveats I mentioned above.