2015-09-17 109 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

谢谢。有用! –