I've just learning about functions and have tried writing my own function up below, to determine the maximum value of 3 values inputted into the system. I have tried to "call" the function before the "main" body and then defined the function below.
It's not quite working though.
I'm confused about the "return" also.. am I doing it right, by defining my final value as "Answer" and then calling it back in the final "return" statement?
#include <stdio.h>
int int_max_3(int, int, int);
int
main(int argc, char **argv) {
printf("The answer is", int_max_3);
return 0;
}
int
int_max_3(int a, int b, int c) {
while(scanf("%d%d%d",&a,&b,&c)==3){
int answer;
if ((a>b) && (a>c)){
answer == a;
printf("%d is the largest number", answer);
break;
}
elseif ((b>a) && (b>c)){
answer == b;
printf("%d is the largest number", answer);
break;
}
else {
answer == c;
printf("%d is the largest number", answer);
break;
}
}
return answer;
}
return can be used to bring back a value or any other thing. it can also be used to bring back whether the function worked properly(code 0) or not(code 1)
You're doing it quite right, but you need to pass some numbers to the function, or it won't have any data to work with. I notice you are requesting the numbers from the user in the in_max function, but it's name suggests it should only find the maximum - not ask the numbers.
#include <iostream> //iostream is preferred in c++ for using std::cout
int int_max_3(int, int, int); //this is called a function prototype
int main(int argc, char **argv) {
int i1, i2, i3; //declare integers
std::cout << "Please enter 3 integers, separated by spaces: ";
std::cin >> i1 >> i2 >> i3; //read user input
//pass the integers to the function and print the result
std::cout << "The answer is "<< int_max_3(i1, i2, i3);
return 0;
}
int int_max_3(int a, int b, int c) {
int answer; //answer variable must be declared or you can't use it
if ((a>b) && (a>c)){
answer == a; //you don't need break; here - only in switch statements or loops
}
elseif ((b>a) && (b>c)){
answer == b;
}
else {
answer == c;
}
return answer;
}
Return values are a way of either getting feedback from a function (for instance if it's operation was succesful) or getting modified values back from the function (for instance int sum(2, 3) would return an integer 5. So in your case you do indeed need to return the answer.