2016-12-02 61 views
0

我想計算兩點之間的距離,但我需要通過使用主函數來完成。我在嘗試確保我的程序返回正確的值時遇到了一些困難。我已經附上了我的代碼,所以如果有人能夠幫助糾正我可能犯了錯誤的部分,我將不勝感激。 (注:我是相當新的C,所以我可能需要了解一些東西一些額外的幫助。)查找C中兩點之間的距離

#include <stdio.h> 
double distance(double x1, double y1, double x2, double y2) 
{ 
    double square_difference_x = (x2 - x1) * (x2 - x1); 
    double square_difference_y = (y2 - y1) * (y2 - y1); 
    double sum = square_difference_x + square_difference_y; 
    double z = 0.00001; 
    for (double i = 0; i < sum; i = i + z) 
    { 
     if (i * i == sum) 
     { 
      return i; 
     } 
    } 
} 

int main(void) 
{ 
    double a = 1.0, b = 2.0, c = 4.0, d = 6.0; 
    double dis; 
    dis = distance(a, b, c, d); 
    printf("The distance of the points (%lf, %lf) and (%lf, %lf) is %lf\n", a,b,c,d,dis); 

    return 0; 
} 

我覺得我的問題是,在主函數中return選項發生雖然我不是這樣如果有的話,確定如何解決這個問題。 `

+4

'distance'很可能不會返回一個值,因爲'i * i == sum'測試很可能會錯過。計算機上的浮點數[通常不準確](http://stackoverflow.com/questions/3730019/why-not-use-double-or-float-to-represent-currency/3730040#3730040),甚至如果是的話,那可能還是經常沒有成功。您可能只想使用''中的'sqrt(sum)',並且比平方根的線性搜索更快。如果你不能,至少,你可能會想要做'我*我> =總和',這可能會在某個時候觸及。 – zneak

+2

另請注意,對於非常大的數字,「i + 0.00001」實際上會返回一個與「i」相同的值,這會使您的程序在無限循環中停頓。 – zneak

+1

'double'的'printf'格式是'%f'。 –

回答

2

這種方式更好,更高效的解決方案。

#include <stdio.h> 
#include <math.h> 

double distance(double x1, double y1, double x2, double y2) 
{ 
    double square_difference_x = (x2 - x1) * (x2 - x1); 
    double square_difference_y = (y2 - y1) * (y2 - y1); 
    double sum = square_difference_x + square_difference_y; 
    double value = sqrt(sum); 
    return value; 
} 
+4

甚至'hypot(x2 - x1,y2 - y1);' –

+0

是的更好。 – MSH

+0

在我正在使用的過程中,我們還沒有使用'#include '來了解平方根函數。有沒有其他方法可以找出'sum'的平方根? –

1

這只是擴展在Weather Vane關於使用斜邊的評論。

#include <stdio.h> 
#include <stdlib.h> 
#include <string.h> 
#include <math.h> 


typedef struct 
{ 
    double x, y; 
} Point; 

typedef struct 
{ 
    Point a,b; 
} Line; 


double length(Line line) 
{ 
    return(hypot(line.b.x - line.a.x, line.b.y - line.a.y)); 
} 


int main(int argc, char *argv[]) 
{ 
    Line line = { {4,0},{0,3} }; 

    printf("Line length = %lf\n", length(line)); 
    return(0); 
} 

這顯示了衆所周知的3,4,5三角形。編譯gcc xxx.c -lm