2012-03-13 12 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

答えて

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

でなければなりません。


また

あなたはdistvoidを使用して値を返さないことを宣言することができます。

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 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を返すように宣言されていますが、何も返されません。あなたは明示的にだけ、次の行を追加します。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を返すか、戻り値の型を変更する必要があります。 リターンzを、そのような質問に対しては -1

+1

それは非常に簡単な質問かもしれませんが、それは非常によく尋ねられました。 – aschepler

+1

あなたは本当にあなたの答えに彼を嫌う必要があると思いますか? – Bart

0

distをdouble( "double dist")に戻すように定義しているので、dist()の最後に "return dist;"または "double dist"を "void dist"に変更する - voidは何も返す必要がないことを意味します。

+0

'return z;'確かに。 ;) – Bart

関連する問題