Function with 2 variable issue, homework help

My code is outputting what is required of it, but when it is run the function output is being placed at the beginning of the cout<< statement and where it is supposed to be is giving a NaN error.

I have checked for uninitialized variables and everything seems correct to me so I don't understand why my output is having such issues.

Any ideas on what's wrong?

output:
" 2The larger of 1 and 2 is nan
2The larger of 2 and 1 is nan

Process returned 0 (0x0) execution time : 0.050 s
Press any key to continue. "

Here is the .cpp

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
#include <iostream>
using namespace std;

float larger(float valA, float valB);

int main()
{
   float num1 = 1, num2 = 2, temp;

   cout << "The larger of " << num1 << " and " << num2
        << " is " << larger(num1, num2) << endl;

   temp = larger(num2, num1);

   cout << "The larger of " << num2 << " and " << num1
        << " is " << temp << endl;

    return 0;
}

float larger(float valA, float valB)
{
    if (valA > valB)
    {
        cout << valA;
    }
    else if (valA < valB)
    {
        cout << valB;
    }
}
You have declared (and called) a float larger() function.

Which means it is supposed to RETURN a float.

But it doesn't return anything.



Let your main function do the cout'ing. Your function should do the return'ing.
Well, that fixes it. Figured it had to be something simple.

Suppose I should read up on when it's appropriate to use cout<< vs RETURN.
Think I get the gist of it, but just to be safe.

Thanks.

Last edited on
Topic archived. No new replies allowed.