当前位置:网站首页>Detailed explanation of C const: definition and use of C constant

Detailed explanation of C const: definition and use of C constant

2022-06-26 13:02:00 Dusk and starry sky

Constants and variables are containers for storing data , When defining, you need to specify the data type , The only difference between them is : Variable (Variable) Values stored in are allowed to be changed , And constant (Constant) The value stored in cannot be changed .

Last section 《C# Variable 》 The definition and use of variables have been explained in , In this section, we will explain the definition and use of constants .
C# Definition of constant
Unlike variables , The value of a constant cannot be changed after it is first assigned . Defining constants requires the use of keywords const To complete .

The specific grammatical form is as follows :
const data type Constant names = value ;

It should be noted that , A constant must be assigned a value when it is defined , Because if you don't assign values, you can't assign values anymore . in addition , You can also define multiple constants at the same time .

Using constants in programs also brings many benefits , It includes enhancing the readability of the program and facilitating the modification of the program . For example, in a program that calculates the rate , In order to ensure the uniform tax rate in the procedure , Set a name to TAX Constant to complete , If you need to modify the tax rate, just modify the value of this constant .

【 example 1】 Find the area and perimeter of the circle respectively , And use constants to store π Value , take π The value of is defined as 3.14.
Copy in plain text
class Program
{
static void Main(string[] args)
{
const double PI = 3.14;
int r = 3; // Storage radius
Console.WriteLine(“ The circumference of the circle is :” + 2 * PI * r);
Console.WriteLine(“ The area of a circle is :” + PI * r * r);
}
}
Execute the code above , The effect is as follows .
 Insert picture description here

原网站

版权声明
本文为[Dusk and starry sky]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/177/202206261220205483.html