0

我正在尝试调用该dist()方法,但是我不断收到错误消息,说dist()必须返回一个值。

// 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);
} 
4

5 回答 5

7

将返回类型更改为 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;
}

或返回函数末尾的值:

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;
}
于 2012-03-13T17:53:10.447 回答
4

dist函数被声明为返回 adouble但不返回任何内容。您需要显式返回z或将返回类型更改为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;
}
于 2012-03-13T17:53:10.490 回答
3

您正在向 STDOUT 输出“结果为 z”,但实际上并未将其作为dist函数的结果返回。

所以

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;
}

应该

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);
}

(假设您仍想打印它)。


或者

您可以使用以下命令声明dist不返回值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;
}

请参阅: C++ 函数教程

于 2012-03-13T17:52:59.957 回答
0

只需添加以下行: return z; -1 对于这样的问题。

于 2012-03-13T17:53:19.333 回答
0

由于您已将 dist 定义为返回 double(“double dist”),因此在 dist() 的底部,您应该执行“return dist;” 或将“double dist”更改为“void dist” - void 表示它不需要返回任何内容。

于 2012-03-13T17:54:47.883 回答