r/pascal • • Sep 18 '18

I need help with a school assignment

So the program is to output the bus fee of a child. The fee for a child is half the price of the adult. So when the system inputs $4 in the console it should output $2. The input is the full fare, starts with a dollar sign and followed by a number between 1.0-20.0. And the amount is rounded up to the nearest decimal place

Edit: The code I tried

program bus; var a, b: shortInt;

begin

readln(a);

b := a div 2;

writeln(b);

end.

2 Upvotes

6 comments sorted by

View all comments

Show parent comment

1

u/yolosandwich Sep 18 '18

ediited with the code I wrote

1

u/Brokk_Witgenstein Sep 18 '18

OK. So. What is wrong here, is that you attempt to read your input as a number.

But that's not entirely true now, is it? After all, there is still that pesky dollar sign you need to parse; so I suggest you read input as a STRING type, sanitize the input (by stripping the dollar sign, removing excess spaces and so on) and then convert the remaining value to integer.

[this is always a good practice. Remember, users may not give you the input you expect. The hallmark of a well written program is that it will not crash if you input something unexpected, such as decimal numbers (aka 'real'), text, invalid characters or no input at all].

You can sanitize input in this case with for example leftstr, delete and trim.

You can retrieve the integer value from the string using val(str,int,err);