Question

I'm trying to call the dist() method however I keep getting a error saying that dist() must return a value.

// creating array of cities
double x[] = {21.0,12.0,15.0,3.0,7.0,30.0};
double y[] = {17.0,10.0,4.0,2.0,3.0,1.0};

// distance function - C = sqrt of A squared + B squared

double dist(int c1, int c2) {
    z = sqrt ((x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
    cout << "The result is " << z;
}

void main()
{
    int a[] = {1, 2, 3, 4, 5, 6};
    execute(a, 0, sizeof(a)/sizeof(int));

    int  x;

    printf("Type in a number \n");
    scanf("%d", &x);

    int  y;

    printf("Type in a number \n");
    scanf("%d", &y);

    dist (x,y);
} 
Was it helpful?

Solution

You are outputting "The result is z" to STDOUT but not actually returning it as the result of the dist function.

So

double dist(int c1, int c2) {

    z = sqrt (
         (x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
      cout << "The result is " << z;
}

should be

double dist(int c1, int c2) {

    z = sqrt (
         (x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
      cout << "The result is " << z;
    return(z);
}

(assuming you still want to print it).


Alternatively

You can declare that dist doesn't return a value using void:

void dist(int c1, int c2) {

    z = sqrt (
         (x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
      cout << "The result is " << z;
}

See: C++ function tutorial.

OTHER TIPS

Either change the return type to void:

void dist(int c1, int c2) {

  z = sqrt ((x[c1] - x[c2] * x[c1] - x[c2]) +
           (y[c1] - y[c2] * y[c1] - y[c2]));
  cout << "The result is " << z;
}

or return the value at the end of the function:

double dist(int c1, int c2) {

  z = sqrt ((x[c1] - x[c2] * x[c1] - x[c2]) +
           (y[c1] - y[c2] * y[c1] - y[c2]));
  cout << "The result is " << z;
  return z;
}

The dist function is declared to return a double but returns nothing. You need to explicitly return z or change the return type to void

// Option #1 
double dist(int c1, int c2) {
    z = sqrt (
         (x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
      cout << "The result is " << z;
    return z;
}

// Option #2
void dist(int c1, int c2) {
    z = sqrt (
         (x[c1] - x[c2] * x[c1] - x[c2]) + (y[c1] - y[c2] * y[c1] - y[c2]));
      cout << "The result is " << z;
}

just add following line: return z; -1 for such question.

Since you have defined dist to return double ("double dist"), on the bottom of dist() you should do "return dist;" or change "double dist" to "void dist" - void means it doesnt need to return anything.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top