How To Write A Calculator Program

Table of contents:

How To Write A Calculator Program
How To Write A Calculator Program

Video: How To Write A Calculator Program

Video: How To Write A Calculator Program
Video: How to Create a Simple Calculator Program using C+ Programming Language ? 2024, May
Anonim

The calculator program is one of the typical programming tasks. Such an application can be implemented in almost any programming language. One of the most popular programming languages is Delphi, which can be used to write simple and efficient calculator code.

How to write a calculator program
How to write a calculator program

Necessary

Delphi programming environment

Instructions

Step 1

Start the Delphi programming environment you are using. Plan your application's interface. There will be 26 buttons on the form, 10 of which are responsible for numbers, and the rest are for functions. Additionally, there will be a TPanel component on which the result of the action will be displayed.

Step 2

Add 4 variables to the code that will store the numbers entered by the user and determine the mode. For example:

var

a, b, c: real; // numbers that the user enters

d: integer; // calculator action

Step 3

The created variables can be added to both protected and private. Now handle the OnClick event for each number button. For all digits, the code will be identical:

procedure TForm1. Button1Click (Sender: TObject);

begin

Panel1. Caption: = Panel1. Caption + 'number'

end;

Replace “number” with the button name (if it is number 0, then Panel1. Caption + '0').

Step 4

The variable d is in integer format and will contain the corresponding numeric value of any action. If multiplication will be carried out, then you can set the action to value 1, if division - value 2, if addition - value 3, etc. For the multiplication action, the code will look like:

procedure TForm1. ButtonMultiplyClick (Sender: TObject); // multiply action

begin

a: = StrToFloat (Panel1. Caption); // after pressing the button, the value of the variable a is saved

d: = 1; // action variable is set to the corresponding value

Panel1. Caption: = '';

end;

Step 5

Do similar operations for division (ButtonDivClick), addition (ButtonPlusClick), subtraction (ButtonMinusClick), and exponentiation (ButtonPowerClick).

Step 6

To process the value `` = '', you need to make a case condition and consider each action in turn:

procedure TForm1. ButtonClick (Sender: TObject);

begin

case d of

1: begin // if d = 1, i.e. the multiplication button is pressed, then the corresponding action occurs

b: = StrToFloat (Panel1. Caption);

c: = a * b;

Panel1. Caption: = FloatToStr (c);

end;

2: begin

a: = StrToFloat (Panel1. Caption);

c: = a / b;

Panel1. Caption: = FloatToStr (c);

Step 7

Handle addition, subtraction, and exponentiation in the same way. The calculator is ready.

Recommended: