Details symbolic constants variables and arithmetic expressions in C

  • 2020-05-05 11:37:43
  • OfStack

The symbolic constant
in the C language Before we conclude our discussion of temperature converters, let's take a look at symbolic constants. Using magic Numbers like 300, 20, etc. in a program is not a good habit. They provide little information to future readers of the program and make it more difficult to modify the program. One way to deal with magic Numbers is to give them meaningful names. The #define directive can define the symbol name (or symbolic constant) as a specific string:


#define  The name   Replace text 

After this definition, all names that appear in the program that are defined in #define (neither enclosed in quotes nor part of any other name) are replaced with the corresponding replacement text. The names are in the same form as ordinary variable names: they are sequences of letters and Numbers beginning with letters; The replacement text can be any sequence of characters, not just Numbers.
After this definition, all names that appear in the program defined in #define (neither enclosed in quotes nor part of any other name) are replaced with the corresponding replacement text. The names are in the same form as ordinary variable names: they are sequences of letters and Numbers beginning with letters; The replacement text can be any sequence of characters, not just Numbers.


#include <stdio.h>

#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */

/* print Fahrenheit-Celsius table */
main()
{
 int fahr;
 for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

Where LOWER, UPPER, and STEP are symbolic constants, not variables, and therefore do not need to appear in the declaration. Symbolic constant names are usually spelled with uppercase letters, which can be easily distinguished from variable names spelled with lowercase letters. Notice that there is no semicolon at the end of the #define command line.

variable and arithmetic expression
for the next program, use the formula ℃=(5/9)(wk-32) to print the following Fahrenheit/Celsius scale:


0 -17
20 -6
40 4
60 15
80 26
100 37
120 48
140 60
160 71
180 82
200 93
220 104
240 115
260 126
280 137
300 148

This program still includes only one function definition called main. It's longer than the previous program that printed "hello, world," but it's not complicated. New concepts were introduced in this program, including comments, declarations, variables, arithmetic expressions, loops, and formatting output. The program looks like this:


#include <stdio.h>
/*  when  fahr=0 . 20 ,...   . 300  When, respectively print Fahrenheit temperature and Celsius temperature comparison table  */
main()
{
 int i;
 int fahr, celsius;
 int lower, upper, step;
 lower = 0; /*  The lower limit of the thermometer  */
 upper = 300; /*  The upper limit of the thermometer  */
 step = 20; /*  Step length  */

 fahr = lower;
 while (fahr <= upper) {
 celsius = 5 * (fahr-32) / 9;
 printf("%d\t%d\n", fahr, celsius);
 fahr = fahr + step;
 }
 scanf("%s", &i);
}

One line:


/* when  fahr=0 . 20 ,...   . 300  When, respectively print Fahrenheit temperature and Celsius temperature comparison table  */

It's called an annotation, and here it simply explains what the program does. Sequences of characters between /* and */ are ignored by the compiler. Comments can be used freely in a program to make it easier to understand. Comments can be used where Spaces, tabs, or newlines are allowed in a program.

In the C language, all variables must be used after the declaration. Declarations are usually placed at the beginning of a function, before any executable statement. Declare an attribute to describe a variable, which consists of a type name and a variable scale, for example,


int fahr, celsius;
int lower, upper, step;

Where the type int means that the variables listed after it are integers, float means that the variables listed are floating point Numbers (that is, Numbers that can have fractional parts). The value range of int and float types depends on the specific machine. For the int type, it is usually 16 bits, with values ranging from -32768 to 32767, and it is also used to represent the int type with 32 bits. The float type is usually 32 bits long and has at least 6 significant digits, with values ranging from 10-38 to 1038.

In addition to int and float types, C provides other basic data types, such as

char: character, one byte short: short integer long: long integer double: double precision floating point

The size of these data type objects also depends on the specific machine. In addition, there are arrays, structures, unions, Pointers to these basic data types, and functions that return values of these types.

In the above temperature converter, the first calculation performed is the following four assignment statements:


lower = 0;
upper = 300;
step = 20;
fahr = lower;

They set the initial value for the variable. Each statement ends with a semicolon.

The lines in the temperature conversion table are calculated the same way, so you can repeat the output lines with a loop statement. This is what the while loop is for:


while (fahr <= upper) {
 ...
}

The while loop is executed by first testing the condition in parentheses; If the condition is true =upper), then execute the body of the loop (three statements enclosed in curly braces); Then re-test the condition in the parentheses, and if true, execute the loop body again. When the condition test result in parentheses is false When upper), the loop ends and continues to execute the next statement after the while loop statement. In this program, there are no other statements after the loop statement, so the execution of the entire program terminates.

The loop body of an while statement can be one or more statements enclosed in curly braces (as in the above temperature converter) or a single statement not enclosed in curly braces, such as


while (i < j)
 i = 2 * i;

In both cases, we always indent statements controlled by while into a TAB so that it is easy to see which statements are included in the loop. This indentation highlights the logical structure of the program. Although the C compiler is not concerned with the appearance of a program, proper indentation and a programming style that preserves appropriate whitespace are important for legibility. We recommend writing only one statement per line and adding a space character to each side of the operator to make the combination of operations clearer. The position of the curly braces is less important. We've chosen one of the more popular styles, so readers can choose a style that works for them and get in the habit of using it all the time.

In this program, most of the work is done in the body of the loop. The assignment statement in the body of the loop:


printf(" %d\t%d\n", fahr, celsius);

Use to print the values of two integers fahr and celsius with a TAB space between them (\t).

Each % in the first argument of the printf function corresponds to the second, third,... Arguments that must match in number and type, otherwise an error result will occur.

Incidentally, the printf function is not part of the C language itself, and the C language itself does not define input/output functionality. printf is just one of the standard library functions that are useful in C programs. However, the ANSI standard defines the behavior of the printf function, so the properties of the function are the same for every compiler and library that meets the standard.

There are two problems with the above temperature conversion program. The simple problem is that the output is not pretty because the Numbers are not right-aligned. This is an easy problem to solve: if you specify the print width in %d of the first argument of the printf statement, the printed number is right-aligned in the print area. For example, use the phrase


#include <stdio.h>

#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */

/* print Fahrenheit-Celsius table */
main()
{
 int fahr;
 for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

0

Print the values of fahr and celsius, so that fahr is 3 digits wide and celsius is 6 digits wide. The output is as follows:


#include <stdio.h>

#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */

/* print Fahrenheit-Celsius table */
main()
{
 int fahr;
 for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

1

Another serious problem is that because we use integer arithmetic, the calculated Celsius temperature value is not very accurate. For example, the exact Celsius temperature corresponding to 0 should be -17.8℃ instead of -17℃. For more accurate results, the integer arithmetic operations above should be replaced by floating point arithmetic operations. This requires appropriate modifications to the program. Here is another version of the program,


#include <stdio.h>

#define LOWER 0 /* lower limit of table */
#define UPPER 300 /* upper limit */
#define STEP 20 /* step size */

/* print Fahrenheit-Celsius table */
main()
{
 int fahr;
 for (fahr = LOWER; fahr <= UPPER; fahr = fahr + STEP)
 printf("%3d %6.1f\n", fahr, (5.0/9.0)*(fahr-32));
}

2

This program is basically the same as the previous program, except that it declares fahr and celsius as float types, and the expression of the conversion formula is more natural. In the previous program, the 5/9 form could not be used because, according to the calculation rule of integer division, they divide and discard to get a result of 0. However, the decimal point in the constant indicates that the constant is a floating point number, so 5.0/9.0 is divided by two floating point Numbers and the result is not truncated.

An integer operation is performed if all operands of an arithmetic operator are integers. However, if an arithmetic operator has a floating point operand and an integer operand, the integer operand will be converted to a floating point before the operation begins. For example, in the expression fahr w32, 32 is automatically converted to a floating point number during the operation. However, even if a floating point constant takes an integer value, it is best to write it with an explicit decimal point to emphasize its floating point nature and make it easy to read.
Note here that the assignment statement fahr = lower; And conditional test statement while (fahr <) = upper) is also executed in such a way that the operands of int type are converted to the operands of float type before the operation.

Conversion specification in printf % 3.0f indicates that the floating-point number to be printed (i.e. fahr) is at least three characters wide and has no decimal point or decimal part; %6.1f indicates that another number to print (celsius) is at least six characters wide and has one digit behind the decimal point. The output is as follows:


 0 -17.8
20  -6.7
40  4.4
...

For example, %6f means that the floating-point number to be printed is at least six characters wide. %.2f specifies that the floating-point number to be printed has two decimal places after the decimal point, but the width is not limited; %f simply requires that the number be printed as a floating point number.

Print %6d as a decimal integer, at least 6 characters wide

In addition, the printf function supports the following format: %o for octal Numbers; %x means hexadecimal number; %c means character; %s for string; %% represents the percent sign (%) itself.


Related articles: