2015-09-17 108 views
0

我正在用帕斯卡爾寫程序。並有條件的一些麻煩。帕斯卡條件的麻煩

例如,如果在輸入

tArea1 = 6和sumAreas = 6太
但在 「如果」 結構這個寫工作不正常。

請幫助我。 TNX。

var 
    x1,x2,x3,x4,y1,y2,y3,y4: real; 
    line1Length, line2Length, line3Length : real; // Length of the triangle area 
    tArea1, tArea2, tArea3, tArea4, sumAreas : real; 

    function segmentLength (x,y,x0,y0:real); 
    begin 
    segmentLength := sqrt(sqr(x-x0) + sqr(y-y0)); 
    end; 

    function triangleArea (a,b,c:real); 
    var 
    p: real; // Half of the perimetr 
    begin 
    p := (a+b+c)/2; 
    triangleArea := sqrt(p*(p-a)*(p-b)*(p-c)); 
    end; 

begin 
    writeln('write x1,y1'); 
    readln(x1,y1); 
    writeln('write x2,y2'); 
    readln(x2,y2); 
    writeln('write x3,y3'); 
    readln(x3,y3); 
    writeln('write x4,y4'); 
    readln(x4,y4); 

    // First triangle 
    line1Length := segmentLength(x1,y1,x2,y2); 
    line2Length := segmentLength(x2,y2,x3,y3); 
    line3Length := segmentLength(x3,y3,x1,y1); 

    tArea1 := triangleArea(line1Length, line2Length, line3Length); 

    // Second triangle 
    line1Length := segmentLength(x4,y4,x2,y2); 
    line2Length := segmentLength(x2,y2,x3,y3); 
    line3Length := segmentLength(x3,y3,x4,y4); 

    tArea2 := triangleArea(line1Length, line2Length, line3Length); 

    // Third triangle 

    line1Length := segmentLength(x4,y4,x1,y1); 
    line2Length := segmentLength(x1,y1,x3,y3); 
    line3Length := segmentLength(x3,y3,x4,y4); 

    tArea3 := triangleArea(line1Length, line2Length, line3Length); 

    // Fourth Triangle 

    line1Length := segmentLength(x4,y4,x1,y1); 
    line2Length := segmentLength(x1,y1,x2,y2); 
    line3Length := segmentLength(x2,y2,x4,y4); 

    tArea4 := triangleArea(line1Length, line2Length, line3Length); 

    // Check dot situated 

    sumAreas := tArea4+tArea2+tArea3; 

    writeln(tArea1, ' // ', sumAreas); // 

    if (sumAreas = tArea1) then 
    begin 
    writeln('In'); 
    end 
    else 
    begin 
    writeln('Out'); 
    end; 

end. 
+3

你在做什麼,你遇到什麼問題? http://stackoverflow.com/help/how-to-ask – hemflit

+0

懶惰的學生的功課? – Marusyk

回答

2

由於計算機表示浮點數的方式,所以在比較看起來相同的兩個數字時可能會出現不一致。與整數不同,IEEE浮點數只是近似值,不是精確的數字。將數字轉換成計算機形式的需要可以以二進制形式存儲,導致較小的精度或舍入偏差。例如1.3可能確實表示爲1.29999999999

因此,您絕對不應該使用=<>來比較兩個浮點數。相反,減去這兩個數字並將它們與一個非常小的數字進行比較。

對於你的情況下嘗試使用:

if abs(sumAreas - tArea1) < 0.00001 then 

有可能使用時的轉換功能,如StrToFloatTextToFloatStrToCurr

if FloatToStr(sumAreas) = FloatToStr(tArea1) then 

而且它,但不建議特別是問題:

if Round(sumAreas) = Round(tArea1) then 

參考: Problems comparing floating point numbers.

+0

ty非常多;) –

+0

你的IF有冗餘括號。:-) –

+0

@MarcovandeVoort你的意思是if(....)then'? – Marusyk

2

您與平等(=)運算符比較浮點值。比較浮點值時,值的差異很小(由於數字原因)會導致偏差,導致比較失敗。

一個更好的等價測試

if abs(value-valuetocompareto)<eps then 
    writeln('bingo') 
else 
    writeln('tryagain'); 

與每股收益的值多少允許偏離適當的寬容。 (嘗試以0.0001開頭)

如果是家庭作業,可以在評論中添加基於邏輯或數字數學的EPS大小的動機。

+0

謝謝。有用! –