计算距离:方法“必须返回一个值”?
-
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”输出到 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++函数教程.
其他提示
要么将返回类型更改为 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 对于这样的问题。
由于您已定义为返回double(“ double dist”),因此在dist()的底部,您应该进行“返回dist;”;或将“双dist”更改为“ void dist” - void意味着它不需要返回任何东西。
不隶属于 StackOverflow