簡體   English   中英

計算距離:方法“必須返回值”嗎?

[英]Calculating distance: method “must return a value”?

我正在嘗試調用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 ++函數教程

只需添加以下行:return z; -1這樣的問題。

由於您已定義dist返回double(“ double dist”),因此在dist()的底部應執行“ return dist;”。 或將“ double dist”更改為“ void dist”-void表示它不需要返回任何內容。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM