Recent

Author Topic: Simple math problem  (Read 1877 times)

AZ26

  • Newbie
  • Posts: 1
Simple math problem
« on: January 30, 2018, 09:49:29 am »
Hi!
Beg you pardon if this was asked Q&A'd before, but I didn't find any by searching this site.
I wrote a little program for testing reasons before I dive deeper into programing with FPC

...
var number: real/single/double/extended; (tried them all successively)
...
readln (number);
writeln (number/2); (I even tried it with 2.0);

Some input give me correct results, like
2.5 -> 1.25000...000E+000
2.6 -> 1.3000...000E+000

Others fail, like
2.7 -> 1.35000...0001E+000
6.6 -> 3.2999...9998E+000

How come? Why that?
To prevent this, what switches or options do I need?


Thanks in advance

paweld

  • Hero Member
  • *****
  • Posts: 970
Best regards / Pozdrawiam
paweld

mig-31

  • Sr. Member
  • ****
  • Posts: 305
Re: Simple math problem
« Reply #2 on: January 30, 2018, 10:20:53 am »
Use RoundTo function
Lazarus 2.2.6 - OpenSuse Leap 15.4, Mageia 8, CentOS 7

wp

  • Hero Member
  • *****
  • Posts: 11858
Re: Simple math problem
« Reply #3 on: January 30, 2018, 10:35:59 am »
If you output a floating point number (single, double, extended) by Write or WriteLn, exponential notation is used by default because this is the only way numbers of any magnitude (within the specification of the data type, of course) can be displayed without dropping digits. If you want "nice" numbers you add two more values, separated by colons. The second one is the number of decimal places, the first one is the total width of the output field - spaces are added at the left if the string is shorter than the width. This is a nice way to right-align numbers. If the parameter is shorter than the string width then output starts immediately at the cursor (no spaces added at the left)

Try this:
Code: Pascal  [Select][+][-]
  1. var
  2.   number: double;  // or single, or extended, or real
  3. ...
  4.   number := 2.5;
  5.   WriteLn(number);
  6.   WriteLn(number:20:1);  // total field width: 20 digits, 1 decimal
  7.   WriteLn(number:20:2);  // dto., but 2 decimal places
  8.   WriteLn(number:0:1);   // total field width not specified, no spaces added to the left, 1 decimal
  9.  

 

TinyPortal © 2005-2018