Return float value from function

Hi, I'm very new to C++ (started learning a few days ago). I'm new to the forums here also, so: Hello all (hello world?), pleased to meet you, I'm Thom.

I'm currently getting to grips with making functions and getting data values to return from them. I'm calculating the distance between two x,y,z points as an exercise (I'll post the full code at the bottom of this post).

I've managed to make it work using 'void' functions, and setting the function to cout the value as a part of it. However, I wanted to get the values out from the function and back into a variables in the main program so have changed the type to 'float'.

In the main the call to the function reads as:

float a = distance(point1, point2);

and the function itself ends by declaring:

return dist;

where 'dist' is the final value.


When I run the program, however, the values come out as 'nan'. I added in an extra line back in to the function to cout the value as well, in case I'd mucked up turning it from a void to a float. This works perfectly and gives the value for each.

I'm assuming I've missed something obvious. However, I've been looking back through other exercises, examples, etc., and can't figure out what it is! Any suggestions as to what I've done wrong?? would be greatly appreciated.

All the best,
Thom.


The code:

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
32
33
34
35
36
37
38
39
40
41
42
#include <iostream>
#include <cmath>


using namespace std;

float distance(float d1[3], float d2[3]);
float distance(float x, float y, float z);

int main()
{
    float point1[3] = {3, 5, 6};
    float point2[3] = {10, 2, 4};
    float point3[3] = {1, 8, 3};

    float a = distance(point1, point2);
    float b = distance(point1, point3);
    float c = distance(point2, point3);

    cout << "The distance between point 1 and point 2 is: " << a << endl;
    cout << "The distance between point 1 and point 3 is: " << b << endl;
    cout << "The distance between point 2 and point 3 is: " << c << endl;
}

float distance(float d1[3], float d2[3])
{
    float d3[3] = {d1[0] - d2[0], d1[1] - d2[1], d1[2] - d2[2]};
    distance(d3[0], d3[1], d3[2]);
}

float distance(float x, float y, float z)
{
    float x2 = x * x;
    float y2 = y * y;
    float z2 = z * z;

    float dist = sqrtf(x2 + y2 + z2);

    cout << "Distance (internal): " << dist << endl;

    return dist;
}




Thanks!!
You are calling this function:

1
2
3
4
5
float distance(float d1[3], float d2[3])
{
    float d3[3] = {d1[0] - d2[0], d1[1] - d2[1], d1[2] - d2[2]};
    distance(d3[0], d3[1], d3[2]);
}


which does not return anything. You need to make that function return a value.
Thank-you - all fixed now!
Topic archived. No new replies allowed.