2017-04-26 128 views
0

我試圖計算2個點之間的距離,A,B。當我運行終端窗口時,它給了我一個錯誤的數字。任何人都可以幫助我改變一些價值,或影響或許多提示。A,B之間的距離

例子: 在答:-50 -50 在B:50 50 距離爲141.42

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

typedef struct{ 
    double a; 
    double b; 
    double c; 
    double d; 
}location; 

double dist(location w,location x, location y,location z) 
{ 
    double l; 
    l=sqrt(pow((y.c-w.a),2)+pow((z.d-x.b),2)); 
    return(l); 
} 

void main() 
{ 
    location h; 
    location i; 
    location j; 
    location k; 
    printf("Enter 1st point(A)\n"); 
    scanf("%lf %lf",&h.a,&i.b); 
    printf("Enter 2nd point(B)\n"); 
    scanf("%1f %1f",&j.c,&k.d); 
    double data; 
    data = dist(h,i,j,k); 
    printf("%.2lf",data); 
} 
+2

141.42是這些點之間的正確歐幾里得距離。你期望的距離是什麼? – user1118321

+3

使用格式'%1f'時,最多隻能讀入一位數字。您似乎錯誤地輸入了小寫字母L,並使用數字1代替。 – paddy

+4

真正的問題是爲什麼在這裏有4個位置(或爲什麼位置有4個東西) – 2017-04-26 05:21:44

回答

2

你注意到在你的兩個scanf格式字符串之間的區別行:

scanf("%lf %lf",&h.a,&i.b); 
scanf("%1f %1f",&j.c,&k.d); 

沒錯!第二行使用%1f而不是%lf。這有一個完全不同的含義,在你的情況是錯誤的。使用%lf

當你得到的結果你不明白,這是一個很好的時間來使用調試器,或添加printf語句來檢查你的變量值與你期望它們是什麼。

0

隨着稻穀的更正,代碼應該可以工作,但我仍然認爲值得一提/糾正較小的錯誤。

首先void main()沒有在標準中定義。 Why is it bad to type void main() in C++

如果您正在使用GCC,請嘗試使用-Wall參數進行編譯。然後你會得到更多的警告,這將有助於你最終編寫更好的代碼。

此外,爲什麼你有4個地點與4名成員?我重構了一下你的代碼,我認爲這個版本更容易閱讀和理解。

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

typedef struct { 
    double x; 
    double y; 
} Point; 

double DistanceBetween(Point p1, Point p2) 
{ 
    Point vector = { 
     p2.x - p1.x, p2.y - p1.y 
    }; 

    return hypot(vector.x, vector.y); 
} 

int main() 
{ 
    Point p1; 
    Point p2; 

    printf("Enter first point: "); 
    scanf("%lf %lf", &p1.x, &p1.y); 

    printf("Enter second point: "); 
    scanf("%lf %lf", &p2.x, &p2.y); 

    double distance = DistanceBetween(p1, p2); 
    printf("The distance is: %lf\r\n", distance); 

    return 0; 
} 
+1

可以用標準函數'hypot()'替換'sqrt(pow(vector.x,2)+ pow(vector.y,2)'' – chux