0

The following code is supposed to divide a sum of money (e.g. : 325.200) into cards of 50, 10, 5 and 1. The rest (the decimal part being shown separately).

program Cards;
uses wincrt;

var
   d50, d10, d5, d1, dm: integer;
   s: real;
begin
   readln(s);
   d50 := trunc(s) div 50;
   d10 := trunc(s) mod 50 div 10;
   d5 := trunc(s) mod 10 div 5;
   d1 := trunc(s) mod 5;
   dm := trunc((frac(s) * 1000));
   writeln('50: ', d50, ' 10: ', d10, ' 5: ', d5, ' 1: ', d1, ' m: ', dm);
end.

A problem arises with the sum 356.200. The shown dm is 199 instead of 200.

  • `356.200` can not be represented as `real` number. For example, if `real` is 64-bit floating point number, then real value of `s` will be `356.19999999999998863131622783839702606201171875`. – user4003407 Jan 01 '17 at 13:56
  • Expecting exact results from calculations with inexact numeric types often leads to disappointment. –  Jan 01 '17 at 13:56
  • 3
    See [Is floating point math broken?](http://stackoverflow.com/q/588004/576719) – LU RD Jan 01 '17 at 13:59
  • Try my [Decimal](http://www.rvelthuis.de/programs/decimals.html) or [BigDecimal](http://www.rvelthuis.de/programs/bigdecimals.html) types for financial calculations. – Rudy Velthuis Jan 01 '17 at 16:15

0 Answers0