计算距离:方法“必须返回一个值”?

时间:2012-03-13 17:51:20

标签: c++ distance square-root

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

5 个答案:

答案 0 :(得分: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;
}

答案 1 :(得分:4)

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

答案 2 :(得分:3)

您正在输出&#34;结果是z&#34;到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);
}

(假设你还想打印它)。


<强>替代地

您可以声明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++ function tutorial

答案 3 :(得分:0)

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

答案 4 :(得分:0)

由于你已经定义了dist来返回double(“double dist”),所以在dist()的底部你应该做“return dist”。或者将“double dist”更改为“void dist” - void表示它不需要返回任何内容。