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