计算距离:方法"must return a value" ?

Calculating distance: method "must return a value"?

本文关键字:value return must 方法 计算 距离      更新时间:2023-10-16

我正试图调用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);
} 

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

dist函数被声明为返回double,但不返回任何内容。您需要显式返回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;
}

您正在将"结果是z"输出到STDOUT,但实际上并没有将其作为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);
}

(假设您仍要打印)。


或者

您可以使用void:声明dist不返回值

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++函数教程。

只需添加以下行:返回z;-1。

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