2012-03-13 52 views
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); 
} 
+3

閱讀有關操作順序。 'x [c1] - x [c2] * x [c1] - x [c2]'不會做你想要的。 – aschepler 2012-03-13 17:58:37

回答

3

您正在輸出「的結果是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); 
} 

(假設你還是要打印)。


或者

你可以聲明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

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

只需添加下面一行: 回報Z者除外; -1這樣的問題。

+1

這可能是一個非常簡單的問題,但問題相當好。 – aschepler 2012-03-13 17:57:29

+1

你真的認爲有必要在你的回答中反駁他? – Bart 2012-03-13 17:59:46

0

既然你已經定義了dist返回double(「double dist」),那麼在dist()的底部你應該做「return dist;」或者將「double dist」改爲「void dist」 - void意味着它不需要返回任何東西。

+0

'return z;'肯定。 ;) – Bart 2012-03-13 18:07:07