距離の計算:方法「値を返す必要があります」?
-
13-12-2019 - |
質問
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);
}
. 解決
「結果はzの場合はzです」と実際にはdist
関数の結果として返さない。
so
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 ++関数チュートリアル。
他のヒント
戻り値を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を返します。 そのような質問のための-1。
DIST()の下部にあるDISIN( "double dist")を返すようにDISTを定義しているので、「戻るdist;」または「二重DIST」を「void dist」に変更する - 無効なことは何も戻る必要がありません。
所属していません StackOverflow