wtd
|
Posted: Sun Oct 10, 2004 12:28 am Post subject: [Ada-tut] Declaring variables and simple math |
|
|
Where do I put variable declarations in an Ada program?
Very simply, variable declarations follow "is" and precede "begin". Let's create a program which declares two integer variables.
code: | procedure Simple_Program is
X : Integer;
Y : Integer;
begin
end Simple_Program; |
Of course, we can simplify that in a way that should look familiar to Turing programmers, or those used to any Pascal-derived language.
code: | procedure Simple_Program is
X, Y : Integer;
begin
end Simple_Program; |
Let's assign some values
Assignment is pretty simple in Ada. Again, it's gonna look quite familiar to our resident Turing programmers.
code: | procedure Simple_Program is
X, Y : Integer;
begin
X := 42;
end Simple_Program; |
Now, for a little simple math
code: | procedure Simple_Program is
X, Y : Integer;
begin
X := 42;
Y := X * 2;
end Simple_Program; |
Type safety and floating point numbers
For safety purposes, Ada95 doesn't make it easy to mix integers and floating point numbers in mathematical operations. Any conversions between types have to be explicit.
So let's start with the program we had earlier, but also declare a float Z with a value of 2. This will also demonstrate the ability to give variables initial values when they're declared.
Note: floating point constants must contain a decimal point.
code: | procedure Simple_Program is
X, Y : Integer;
Z : Float := 2.0;
begin
X := 42;
Y := X * 2;
end Simple_Program; |
Now, to do some math mixing integers and floating point numbers. Let's divide X by Z and put the result back in X.
code: | procedure Simple_Program is
X, Y : Integer;
Z : Float := 2.0;
begin
X := 42;
Y := X * 2;
X := X / Integer(Z);
end Simple_Program; |
Of course, it's possible to use something like:
To convert an integer into a float. |
|
|