计算距离:方法"must return a value" ?
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++函数教程。
只需添加以下行:返回z;-1。
由于您已经将dist定义为返回double("double-dist"),因此在dist()的底部应该执行"return dist;"或将"double-dist"更改为"void dist"-void意味着它不需要返回任何内容。
相关文章:
- 方法错误"not all control paths return a value"和方法不返回值
- 如何解决类成员函数中的"return a value"错误?
- QThread start() return value
- 警告:"Not all control paths return a value" c++
- What value should `std::stringstream::fail()` return after r
- Return value of std::hash ofr (x86/x64)
- 在这个程序中"getavg must return value"意味着什么?
- OpenCV HOGDescriptor return value
- 虚假"<function> is expected to return a value"警告?
- Opencv cv::waitKey() return value
- 我返回一个值,但编译器告诉我"function must return a value"
- const object&return value from a method, best practice
- 循环函数给出"return’ with a value, in function returning void"误差
- Return-value C++
- 计算距离:方法"must return a value" ?
- c++ rapidjson return value
- C++错误"not all control paths return a value"
- 当您使用 std::move 返回时,"return-by-rvalue-ref" 和 "return-by-value" 之间的区别?
- CAsyncSocket receive() return value
- boost program_options add_options return value