Content of the lesson:
To let our programs solve more difficult problems you have to use more functions like powers and roots. We are going to show these function inside the Delphi 7 program.
Note: To be able to use these functions you have to add math library inside the uses section. A library is a file which contains pre-programmed functions (for example mathematical) which can be used after inserting the library, otherwise our program would not be able to use these functions and it would report a problem.
Program Matematika;
uses SysUtils, Math;
...
To compute powers you can use the Power function in Delphi. Using the help in Delphi you can see this:
Function Power(Base, Exponent: Extended): Extended;
xy = exp(y * ln(x))
Raise Base to any power, Base > 0
The definition says that this function has two parameters:
In case you want your program to compute and write the result of the expression a5 you have to write writeln(power(a,5));
To compute the square root function you can use the sqrt function (shortcut for square root). Using the help in Delphi you can see this:
Function Sqrt(X: Extended): Extended;
square root: sqrt(x) = x0.5
The power and sqrt function use the real numbers so you have to use another types of variables when working with these functions. You have to use the real (or extended) data type, the real type is used for storing decimal numbers.
Program Mocnina_cisla;
var a,b,e:real;
begin
writeln('Set the base:');
readln(a);
writeln('Set the exponent:');
readln(e);
b:=power(a,e);
writeln('The expression ',a,'^',e,'=',b);
readln;
end.
If you look at the result, you see this: 2,780734536237E0002. What does it mean? It is a scientific notation of a real number. The E letter with the number 0002 means 100002=102. The result is 2,780734536237 multiplied by 102. Such a result is correct but not very useful for a common user so we have to improve our program:
Program Mocnina_cisla;
var a,b,e:real;
begin
writeln('Set the base:');
readln(a);
writeln('Set the exponent:');
readln(e);
b:=power(a,e);
writeln('The expression ',a,'^',e,'=',b:5:7);
readln;
end.
What did we change? We added two more numbers separated by a colon when writing the b variable to console. The first number tells the program to write 5 digits at least (5 digits to a row) - this is not very important for us. Important is the second value which tells the program to write the number using 7 decimal places. In general you can set any number and change the final result. The previous decimal number should now be written as 278,0734536.
You can need the Pi number when computing mathematical formulas. You can use the pi constant in Delphi instead of trying to define its value inside a variable.
Write a program to compute the capacity of any cylinder and any sphere (user should be able to set values). Find required formulas in the Internet.
Write a program to compute this formula: ax+by. User should be able to set all values.