Seven crackers, two plates, and a compiler objection

Go down

Seven crackers, two plates, and a compiler objection

· #1

I declared the cracker count and plate count as integers. Assigning their / result to another integer fails. I expected three crackers per plate and one remaining cracker.

Also, my first attempt to inspect the word crackers used index zero. I have carried two habits over from web development, and neither has helped with lunch.

Re: Seven crackers, two plates, and a compiler objection

· #2

Division and indexes

/ performs real division even when both operands are integers. Use div for an integer quotient and mod for the remainder. The arithmetic operator reference describes the distinction.

Expression Result Meaning
7 / 2 3.5 Real quotient
7 div 2 3 Integer quotient
7 mod 2 1 Remainder

This complete console example also shows ordinary string indexing:

pascal
program SnackMath;
{$mode objfpc}{$H+}
var
  Snack: string;
  Quotient: Double;
begin
  Snack := 'crackers';
  Quotient := 7 / 2;
  WriteLn(Quotient:0:1);
  WriteLn(7 div 2);
  WriteLn(7 mod 2);
  WriteLn(Snack[1]);
end.

The first character is at index 1. Check that a string is nonempty before accessing its first character. Dynamic arrays start at zero, so do not apply the string rule to every container.

Re: Seven crackers, two plates, and a compiler objection

· #3

That gives me exactly the result I wanted. I also changed my string loop to start at 1 and end at Length(Snack).

I had assumed one indexing convention covered the entire language. That was a confident four minutes.

Re: Seven crackers, two plates, and a compiler objection

· #4

wait the slash was working the whole time

Re: Seven crackers, two plates, and a compiler objection

· #5

Yes. I once rounded a division result to make a compiler error disappear. The inventory report then promised half a shelf more stock than we owned.

Choose the operation before choosing how to silence the error.

Pete · thirty years of begin and end "It compiled on my machine."

Re: Seven crackers, two plates, and a compiler objection

· #6

Solved. Three crackers on each plate, one for the programmer. This is the first remainder I have documented.

Go up

Sign in to reply