0

Practice 38.2 Roll the dice

Can someone help? I solved the practice as below, however there is a strange behavior which doesn't make sense. if I declare a variable "result" inside "max" function's body like that int max(int num1, int num2) { int result; if (num1 >= num2){ int result = num1; } else result = num2; return result; } the output fails to solve the practice if the input values are equal; meaning that only test cases 2 & 3 are solved correctly and the rest are incorrect. if I declare the variable "result" as a parameter like that int max(int num1, int num2, int result) { if (num1 >= num2){ int result = num1; } else result = num2; return result; } all test cases are then marked correct {{my question is}} what is the difference between declaring a variable inside the function's body and declaring it as a parameter/argument? in other words why would the first solution's output be not working when the input values are equal and second solution works? solved practice code #include <iostream> using namespace std; int max(int num1, int num2, int result) { //complete the function if (num1 >= num2){ int result = num1; } else result = num2; return result; } int main() { //getting inputs int first; cin >> first; int second; cin >> second; //call the function and print result cout << max(first, second); return 0; } thanks in advance!

29th May 2022, 5:49 PM
Ahmad
Ahmad - avatar
3 Respuestas
+ 3
The first part I can see being an issue is that you declare "int" twice. You only need to do that once, so int result; If(num...) result = num1; should work
29th May 2022, 6:04 PM
Ausgrindtube
Ausgrindtube - avatar
+ 3
In your first method you create two variables result. One above the if else statement (#1) and one inside the if block (#2) The if block sees only #2 and the else block sees only #1 int max(int num1, int num2) { int result = 0; if (num1 >= num2){ //don't write int result result = num1; } else result = num2; return result; }
29th May 2022, 6:10 PM
Denise Roßberg
Denise Roßberg - avatar
+ 1
I see now that the extra "int" was causing a conflict along with the extra "result". Thanks
29th May 2022, 7:30 PM
Ahmad
Ahmad - avatar