Detailed explanation of symbolic constants, variables and arithmetic expressions in C language _c language

Source: Internet
Author: User
Tags arithmetic comparison table constant function definition integer division numeric

Symbol constants in the C language
Let's take a look at the symbolic constants before we end the discussion of the temperature conversion program. It is not a good practice to use similar "magic numbers" in 300, 20, and so on in a program, and they are almost impossible to provide information to those who read the program later, and make it more difficult to modify the program. One way to deal with this magic number is to give them meaningful names. #define directive can define a symbol name (or symbolic constant) as a specific string:

Replace text #define Name

After this definition, all the names that appear in the program in the #define (which are not enclosed in quotation marks or part of other names) are replaced with the corresponding replacement text. Where the names are the same as the normal variable names: They are alphabetical and numeric sequences, and the replacement text can be any sequence of characters, not just numbers.
After this definition, all the names that appear in the program in the #define (which are not enclosed in quotation marks or part of other names) are replaced with the corresponding replacement text. Where the names are the same as the normal variable names: They are alphabetical and numeric sequences, and the replacement text can be any sequence of characters, not just numbers.

#include <stdio.h>

#define LOWER 0/* LOWER limit of Table * * * * *
#define UPPER/* UPPER Limit * *
#defin E Step/* 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 in uppercase letters, which makes it easy to distinguish between variable names that are spelled in lowercase letters. Note that there is no semicolon at the end of #define instruction line.

Variables and arithmetic expressions
Let's take a look at the next program, using the formula ℃= (5/9) (℉-32) to print the following Fahrenheit temperature and Celsius comparison table:

0-17
20-6
4 (
220)
140
160-
180
-M
126
280 137
300 148

Only one function definition named Main is still included in this program. It's a bit longer than the previous "Hello, World" program, but it's not complicated. Some new concepts are introduced in this program, including annotations, declarations, variables, arithmetic expressions, loops, and formatted output. The program looks like this:

#include <stdio.h>
/* When fahr=0,20, ..., 300, respectively dozen Inhua temperature and Celsius temperature comparison table *
/main ()
{
 int i;
 int Fahr, celsius;
 int lower, upper, step;
 lower = 0; /* The lower limit of the temperature meter
 /upper = 300;/* The upper limit of the temperature meter/
 step = 20;///

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


One of the rows:

/* When the fahr=0,20, ..., 300, respectively dozen Inhua temperature and Celsius temperature comparison table * *

Called a comment, here, it simply explains what the program is for. The sequence of characters contained between/* and * * is ignored by the compiler. Annotations are free to be used in programs, making the program easier to understand. You can use annotations when spaces, tabs, or line breaks are allowed in your program.

In the C language, all variables must be declared before they are used. A declaration is usually placed at the beginning of a function before any executable statement. Declares a property that describes a variable, consisting of a type name and a variable table, for example:

int Fahr, celsius;
int lower, upper, step;

where the type int indicates that the variables listed subsequently are integers, and the float indicates that the variables listed are floating-point numbers (that is, numbers that can have a decimal part). The range of int and float type depends on the specific machine. For type int, typically 16 bits, with a value range between -32768~32767 and a 32-bit int type. Float type is usually 32-bit, it has at least 6 digits of valid digits, the value range is generally between 10-38~1038.

In addition to the int and float types, high C also provides some other basic data types, such as:

    • Char: character, one byte
    • Short: Shorter integral type
    • Long: Length-integer
    • Double: double-precision floating-point type

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

In the above temperature conversion program, the first calculation to be performed is the following 4 assignment statements:

lower = 0;
upper =;
Step =;
Fahr = lower;

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

The rows in the temperature conversion table are calculated the same way, so you can repeat the output lines with a loop statement. This is the purpose of the WHILE loop statement:

while (Fahr <= Upper) {
 ...
}

While loop statements are executed by first testing the conditions in parentheses, and if the condition is true (fahr<=upper), execute the Loop body (3 statements enclosed in curly braces), and then test the conditions in parentheses, and if true, execute the loop body again When the conditional test result in parentheses is False (Fahr>upper), the loop ends, and the next statement following the While Loop statement continues to execute. In this program, there are no other statements after the loop statement, so the execution of the entire program terminates.

The loop body of a while statement can be one or more statements enclosed in curly braces (such as the temperature converter above), or a single statement that includes no curly braces, for example:

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

In both cases, we always indent statements that are controlled by while to a tab stop, so that we can easily see which statements are included in the loop statement. This indentation mode highlights the logical structure of the program. Although the C compiler does not care about the appearance of the program, the proper indentation and the design style of the program that retains the appropriate space are important to the readability of the program. We recommend that you write only one statement per line, plus a space character on either side of the operator, which makes the associative relationship of the operation clearer. In contrast, the position of the curly braces is less important. We have chosen one of the more popular styles, and the reader can choose a style that suits them and develop a habit of using the style all the time.

In this program, most of the work is done in the loop body. Assignment statements in the loop body:

printf ("%d\t%d\n", Fahr, Celsius);

Use to print the value of two integers fahr and Celsius, and leave a tab space between the two (\ t).

The individual% of the first argument of the printf function corresponds to the second, third 、...... parameters, they must match on both number and type, otherwise the error results.

Incidentally, the printf function is not part of the C language itself, and the C language itself does not define the input/output functionality. printf is only a useful function in standard library functions, and these standard order functions are usually available in C language programs. However, the ANSI standard defines the behavior of the printf function, so the properties of the function are the same for each compiler and library that conforms to that standard.

The above temperature conversion program has two problems. The simple problem is that because the number of outputs is not right-aligned, the output is not very attractive. This problem is easier to solve: if you indicate the print width in%d of the first parameter of the printf statement, the printed number is right-aligned in the print area. For example, you can use a statement

printf ("%3d%6d\n", Fahr, Celsius);

Print Fahr and Celsius values so that the Fahr value is 3 digits wide and the Celsius value is 6 digits wide, and the output results are as follows:

 0-17  -6 (  4
).

Another serious problem is that because we are using integer arithmetic, the calculated temperature of Celsius is not very accurate, for example, the exact Celsius temperature corresponding to 0℉ should be-17.8 ℃, not 17 ℃. In order to obtain more accurate results, floating-point arithmetic operations should be substituted for the integer arithmetic operations above. This requires proper modification of the procedure. Here is another version of the program

#include <stdio.h>
/* Print Fahrenheit-celsius table for
Fahr = 0, ..., floating-point version */
   main ()
{
 float Fahr, celsius;
 float lower, upper, step;
 lower = 0;
 upper =;
 Step =;
 /* Lower limit of temperatuire scale
 /* Upper Limit/* * Step
 size
 /Fahr = lower;
 while (Fahr <= Upper) {
 Celsius = (5.0/9.0) * (fahr-32.0);
 printf ("%3.0f%6.1f\n", Fahr, Celsius);
 Fahr = Fahr + step;
 }

This program is basically the same as the previous one, but it also declares Fahr and Celsius as float type, and the conversion formula is more natural. In the previous program, the 5/9 form was not used because of the calculation rules for integer division, where the result of dividing and rounding was 0. However, the decimal point in the constant indicates that the constant is a floating-point number, so the 5.0/9.0 is divided by two floating-point numbers, and the result will not be a bit.

An integer operation is performed if all the operands of an arithmetic operator are of an integral type. However, if an arithmetic operator has a floating-point operand and an integer operand, the integer operand will be converted to a floating-point type before the start of the operation. For example, in an expression fahr–32, 32 is automatically converted to floating-point numbers and then participate in operations during the operation. However, even if a floating-point constant takes an integer value, it is best to add an explicit decimal point to it when writing, which emphasizes its floating-point nature and is easy to read.
Notice here that the assignment statement Fahr = lower; and a conditional test statement while (Fahr <= Upper) is also performed in this manner, by converting the operand of type int to an operand of type float before the operation.

The conversion instructions in printf%3.0f indicate that the floating-point number (i.e. Fahr) to be printed is at least 3 characters wide and does not have a decimal point and fractional part,%6.1f indicates that the other to be printed (Celsius) is at least 6 words wide and has a 1-digit number after the decimal point. The output looks like the following:

 0-17.8  -6.7  4.4
...

The format description can omit width and precision, for example,%6f indicates that the floating-point number to be printed is at least 6 characters wide;%.2f Specifies that there are two decimal places for floating-point numbers to be printed, but the width is not limited, and%f only requires that the numbers be printed in floating-point numbers.

    • %d, print in decimal integer
    • %6d, print in decimal integer, at least 6 characters wide
    • %f, printing in floating-point numbers
    • %6f, print at least 6 characters per floating-point number wide
    • %.2f, print at least 6 characters per floating-point number wide
    • %6.2f, print at least 6 characters wide, with two decimal digits after the decimal point.

In addition, the printf function also supports the following format descriptions:%o Represents the number of octal;%x represents the hexadecimal number;%c represents a character;%s represents a string;% percent represents itself.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.