2015-12-09 40 views
-3

我有一個點(x1, y1)和一條線y = m.x + q。而且,我的任務是找到給定點和線之間的最短距離。C程序來計算一個點和一條線之間的距離

下面是我的C代碼相同。

有人能幫助我與我的代碼,因爲它給了我一個位錯誤(錯誤答案)

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

double x1,y1,m,q,distance; 

int main() { 

    printf ("Enter the coefficient 'm' of the line: \n"); 
    scanf ("%lf", &m); 
    printf ("Enter the coefficient 'q' of the line: \n"); 
    scanf ("%lf", &q); 
    printf ("Enter the value of x1: \n"); 
    scanf ("%lf", &x1); 
    printf ("Enter the value of y1: \n"); 
    scanf ("%lf", &y1); 

    distance = (fabs (y1 - (m * x1 - q)))/(sqrt (1 + m * m)); 

    printf ("The distance is %.3f \n", distance); 
} 
+2

你需要發佈錯誤,在片段和更重要的部分。對問題進行高級別概述也有助於SO社區解決您的問題。 – wgwz

+1

請提供樣本輸入,預期輸出和觀測輸出。 –

+3

*什麼*錯誤?它沒有編譯?它崩潰了嗎?它給你意想不到的輸出?你是否確保數學庫正確鏈接? –

回答

1

我猜你會犯錯,而計算公式爲點(x1, y1)之間的距離和行y = m.x + q

替換:

distance = (fabs (y1 - (m * x1 - q)))/(sqrt (1 + m * m)); 

有了:

distance = (fabs (y1 - m * x1 - q))/(sqrt (1 + m * m)); 

編輯:看你一直在得到編譯錯誤是因爲y1已經在math.h聲明的原因頭文件。而且,我猜如果我沒有錯,你必須使用C++編譯器來編譯你的代碼。

... Rest of the upper code of math.h header file 
_CRTIMP double __cdecl j0 (double); 
_CRTIMP double __cdecl j1 (double); 
_CRTIMP double __cdecl jn (int, double); 
_CRTIMP double __cdecl y0 (double); 
_CRTIMP double __cdecl y1 (double);  // y1 is declared here 
_CRTIMP double __cdecl yn (int, double); 

_CRTIMP double __cdecl chgsign (double); 

... Rest Code 

DO:在C程序文件改變變量y1一些,別的東西的名稱。

+0

這是錯誤:「將'y1'重新定義爲不同類型的符號 double x1,y1,m,q,distance;」 ; 「警告:format指定類型'double *',但參數的類型爲'double(*)(double)'」; 「無效的操作數到二進制表達式('double(*)(double)'和'double') distance =(fabs(y1-m * x1 -q))/(sqrt(1 + m * m));」 –

+0

我解決了!問題是變量y1的名稱:我用y替換了名稱,它起作用了! ...但我不明白爲什麼...... –

+0

錯誤在'punto_retta.h' – stark

相關問題