IC004 – Constants in C++

Feiyu BLOG 2023.3.31-

Information Technology Education

Python-Based Teaching

Research Topics

Academic Level Examination

Python Program Design

C++ Informatics

……

IC004 - Constants in C++IC004 - Constants in C++

Constants refer to specific numbers or characters used in a program. During the execution of the program, their values cannot be changed.

Definition of Constants:

Format 1: const type_specifier constant_name

For example: const int X=2 indicates that constant X is defined as 2

Format 2:#define symbolic_constant constant

For example:#define PI 3.14 indicates that PI is defined as 3.14

Exercise: Calculation of the speed of free fall

#include <iostream>
using namespace std;
const float G=9.78;
int main(){
    float v,t;
    t=10;
    v=G*t;
    cout<<"The speed of the iron ball hitting the ground is "<<v<<" meters/second";
}

Debugging Result:

IC004 - Constants in C++

Constants include integer constants, floating-point constants, and character constants.

Constants that represent integers are called integer constants, for example: 3, -5, 0

Constants that represent real numbers are called floating-point constants, for example: 3.1, 3.6

Characters enclosed in single quotes are called character constants, for example: ‘h’, ‘5’

Note: ‘a’ represents a character constant, while “a” represents a string; the two meanings are different.

When defining constants, uppercase letters are generally used.

Exercise:

1. The following program is used to calculate the area of a circle; find the errors that occur in it.

#include <iostream>
using namespace std;
#define PI=3.14;
int main(){
    double s,r,PI;
    cin>>r;    // Input the value of r
    s=r*r*PI;
    cout<<"s="<<s;
}

Error 01: _________________

Error 02: _________________

2. Try programming to input the weight of an apple m and output the gravitational force on the apple.

IC004 - Constants in C++1.IC002 – C++ Writing Hello World2.CSP-J/S Examination3.Informatics Competition 001 – Dev C++ Installation4.IC003 – Variables in C++IC004 - Constants in C++

Improve1% every day, and after a year you can achieve37 times growth; if you regress1% every day, after a year you will weaken, even regress to zero; a small change or a good habit can produce an amazing compounding effect!

Leave a Comment