Introduction to C Programming for classic (version 5th)

Source: Internet
Author: User
Tags modulus

Now, the reader must be eager to write programs to allow actual interaction between the computer and the outside world. We do not want the program to only work as a typist and display fixed information contained in the program code. Indeed, the meaning of programming is far more than that. Ideally, we should be able to input data from the keyboard so that the program can store them somewhere, which will make the program more diverse. The program can access and process the data, and each execution can process different data values. Entering different information each time you run a program is the key to the entire programming industry. Data items stored in a program can be changed, so they are called variables. This is the topic of this chapter.

Main content of this chapter:

● Memory usage and variable concepts

● How to calculate in C

● Different types of variables and their usage

● Concept and application of forced type conversion

● Compile a program to calculate the height of trees

2.1 computer memory

First, let's take a look at how the computer stores the data that the program processes. To this end, we need to understand the computer memory. before writing the first program, we will briefly introduce the computer memory.

When a computer executes a program, the commands of the program and the data operated by the program must be stored somewhere. This is the machine memory, also known as main Memory, or Random Access memory (RAM ). RAM is a volatile memory. After the PC is disabled, RAM content will be lost. The PC uses one or more disk drives as its permanent storage. Any data to be stored after execution of the program should be printed out or written to the disk, because the results stored in RAM will be lost at the end of the program.

You can think of the computer's RAM as an orderly box. Each box has two statuses: full and empty. Therefore, each box represents a binary number: 0 or 1. Computers sometimes use true or false to indicate them: 1 is true, 0 is false. Each box is called-bit, short for binary digit.

Note:

If you do not remember or have never learned binary numbers, refer to Appendix. But if you do not understand the content, don't worry, because the key here is that the computer can only process 0 and 1, rather than the decimal number. All data (including program commands) used by the program is composed of binary numbers.

For convenience, 8 bits in the memory are-groups, and the 8 bits in each group are called one byte ). Each byte is represented by a number. The first byte is represented by 0, and the second byte is represented by 1 until the last byte in the computer memory. The Byte mark is called the address of the byte ). Therefore, each byte address is unique. Each house has a unique street address. Similarly, the byte address uniquely represents the bytes in the computer memory.

In short, the minimum unit of memory is bit, which combines eight digits into a group, called bytes ). Each byte has a unique address. The Byte address starts from 0. The bits can only be 0 or 1-1.

 

Figure 2-1 bytes in memory

The common unit of computer memory is kilobytes (KB), megabytes (MB), and gigabytes (GB ). Large disk drives use megabytes (TB ). The significance of these units is as follows:

● 1 kb is 1 024 bytes.

● 1 MB is 1 024KB, that is, 1 048 576 bytes.

● 1 GB is 1 024 MB, that is, 1 073 741 841 bytes.

● 1 TB is 1 024 GB, that is, 1 099 511 627 776 bytes.

If the PC has 1 gb ram, the byte address is 0 ~ 1 073 741 841. Why not use simpler integers, such as thousands, millions, or hundreds of millions? Because there are a total of 1023 numbers from 0 to 1024, and in binary, the 10 digits of 1023 are exactly l: 11 1111 1111, which is a very convenient binary number. 1000 is a very useful decimal number, but it is no longer so convenient in binary computers. It is 111110 1000. Therefore, the Unit is KB (1 024 bytes) to facilitate computer use. Similarly, MB requires 20 digits, and GB requires 30 digits.

However, the disk capacity may be messy. Disk manufacturers often claim that the capacity of the disks they produce is 256 billion GB or 1 TB, and in fact these two numbers represent 1 trillion bytes and bytes. Of course, 256 billion bytes only 231 MB, and 1 trillion bytes only 911 GB. Therefore, the hard disk capacity provided by the disk manufacturer is misleading.

With the concept of byte, let's take a look at how to use the memory in the program.

2.2 What is a variable

A variable is a specific memory in a computer. It is composed of one or more consecutive bytes, generally 1, 2, 4, 8, or 16 bytes. Each variable has a name that represents the location of the memory to extract the data it contains or store a new value.

Next, write a program and use the printf () function introduced in chapter 1st to show your salary. If your salary is RMB/month, you can easily write this program.

// Program 2.1 What is a Variable?

# Include

Int main (void)

{

Printf (My salary is $10000 );

Return 0;

}

There is no need to explain how this program works. It is similar to the program developed in Chapter 1. How can I modify this program so that it can customize the information to be displayed based on the value stored in the memory? There are several methods that have one thing in common: using variables.

In this example, you can allocate a memory named salary and store the value of 10 000 in this variable. To display the salary, you can use the name salary specified for the variable to display the value of 10 000 stored in it. When a program uses a variable name, the computer accesses the value stored in it. The number of times variables are used is unrestricted. When the salary changes, as long as the salary variable storage value is changed, the entire program will use the new value. Of course, in a computer, all values are stored as binary numbers.

There is no limit on the number of variables in the program. During program execution, the values contained in each variable are determined by the program instructions. The variable value is not fixed, but can be changed at any time, and there is no limit on the number of times.

Note:

A variable can contain one or more bytes. How many bytes does the computer know about the variable? As mentioned in the next section, each variable has a type to specify the data types that can be stored by the variable. The variable type determines how many bytes are allocated to it.

Variable name

The name specified for the variable is generally called the variable name. Variable naming is flexible. It can be one or more upper or lower case letters, numbers, and underscores (_) (sometimes underlines are also counted as letters), but must begin with a letter. The following are some correct variable names:

Radius diameter Auntie_May Knotted_Wool D678

Variable names cannot start with numbers, so 8_Ball and 6_pack are invalid names. Variable names can only contain letters, underscores, and numbers, so Hash! And Mary-Lou cannot be used as variable names. Mary-Lou is a common error, but Mary_Lou is acceptable. There is no space in the variable name, so Mary Lou will be treated as two variable names Mary and Lou. Variable names starting with one or two underscores are often used in header files. Therefore, do not use underscores as the first character when naming variables to avoid conflicts with variable names in the standard library. For example, it is better to avoid using variable names such as _ this and _ that. Another key point of the variable name is that the variable name is case sensitive, so Democrat and democrat are different.

You can specify a variable name at will within the preceding limits, but it is recommended that the variable name be used to help you understand the content contained in the Variable. For example, it is not good to store salary information using the variable name x, the use of the variable name salary is much better, and there is no doubt about its purpose.

Warning:

The number of characters that a variable name can contain depends on the compiler. a c-language-compliant compiler supports at least 31 characters, so long as the length does not exceed this length. It is recommended that the variable name should not exceed this length, because such a variable name is cumbersome and difficult to understand in the code. Some compilers truncate variable names that are too long.

2.3 store Integer Variables

There are several different types of variables, each of which is used to store specific types of data. There are several variables that can store integer, non-integer values and characters. Some types store specific data (such as integers). The difference between them is the amount of memory they occupy and the value range they can store. First, let's take a look at the variables used to store integers.

An integer is a number without a decimal point. The following is an example:

123 10,999,000,000 20,000 88 1

These values are integers, but they are not completely correct for the program. An integer cannot contain commas (,). Therefore, the second value in the program should be 10999000000, and the third value should be 20000.

The following are some examples that are not integers:

1.234 999.9 2.0-0.0005 3.14159265

2.0 is generally counted as an integer, but the computer does not count as an integer because it has a decimal point. In the program, you must write this number 2 without the decimal point. In the C program, integers are always written as numbers without a decimal point. If a number contains a decimal point, it is not an integer, but a floating point. For details, see the following content. Before discussing Integer Variables in detail, let's take a look at a simple variable in the program and learn how to use the variable.

Try again: Use Variables

Return to the example of output salary. Change the previous program to an int variable:

// Program 2.2 Using a variable

# Include

Int main (void)

{

Int salary; // Declare a variable called salary

Salary = 10000; // Store 10000 in salary

Printf (My salary is % d., salary );

Return 0;

}

Enter this example to compile, link, and execute. the following result is displayed:

My salary is 10000.

Code Description

The first three rows are the same as the previous example. Let's look at the new statements. The variable declaration statement used to store salaries is as follows:

Intsalary; // Declare a variable called salary

This statement is called a variable Declaration because it declares the variable name. In this program, the variable name is salary.

Warning:

The variable declaration statement ends with a semicolon. If a semicolon is missing, an error occurs during program compilation.

The variable Declaration also specifies the Data Type stored in this variable, which is specified by the keyword int, and salary is used to store an integer. Put the keyword int before the variable name. This is one of the several types that can be used to store integers.

As described later, when declaring variables that store other data types, you must use another keyword to specify the data type. The method is roughly the same.

Note:

The keyword is a special reserved C word, which has special significance for the compiler. They cannot be used as variable names or other entities in code. Otherwise, the compiler will generate an error message.

A variable Declaration is also called a definition of a variable because it allocates some storage space to store integer values. This integer can be referenced by the variable name salary.

Note:

The Declaration introduces a variable name, And the definition assigns a bucket to the variable. The reason for this difference will be clear later in this book.

Of course, the salary value of the variable has not yet been specified, so the variable now contains a garbage value, that is, the value left here when this memory space was used last time.

The next statement is:

Salary = 10000; // Store 10000 in salary

This is a simple arithmetic value assignment statement that stores the values on the right of the equal sign in the variable on the left of the equal sign. The variable salary is declared here, and its value is 10 000. Store the value 10 000 on the right to the variable salary on the left. Equal sign "=" is called the value assignment operator, which assigns the value on the right to the variable on the left.

 

 

The familiar printf () Statement is followed, but the usage here is slightly different from the previous one:

Printf (My salary is % d., salary );

There are two parameters in the brackets, separated by commas. The parameter is the value passed to the function. In this program statement, the two parameters passed to the printf () function are as follows:

● Parameter 1 is a control string used to control the way in which subsequent parameter output is displayed. It is a string placed in double quotation marks, also known as a format string, because it specifies the format of output data.

● Parameter 2 is the variable name salary. The display method of this variable value is determined by the first parameter-control string.

This control string is similar to the previous example and contains the text to be displayed. However, in this example, this string contains a % d, which is called the conversion Descriptor (conversion specifier) of the variable value ).

The conversion specifiers determine how variables are displayed on the screen. In other words, they specify the format of the original binary value conversion and display it on the screen. In this example, d is used, which is a decimal specifier applied to the integer, indicating that the second parameter salary is output as a decimal number.

Note:

Conversion specifiers always start with % characters so that the printf () function can recognize them. % In the control string always indicates the start of the conversion specifier. to output % characters, you must use the escape sequence %.

Try again: use more variables

Try a slightly larger program:

// Program 2.3 Using more variables

# Include

Int main (void)

{

Int brothers; // Declare a variable called brothers

Int brides; // and a variable called brides

Brothers = 7; // Store 7 in the variable brothers

Brides = 7; // Store 7 in the variable brides

// Display some output

Printf (% d brides for % d brothers, brides, brothers );

Return 0;

}

The execution result is as follows:

7 brides for 7 brothers;

Code Description

This program is quite similar to the previous example. First, declare two variables brothers and brides. The statement is as follows:

Int brothers; // Declare a variable called brothers

Int brides; // and a variable called brides

Both variables are declared as int type, and they both store integer values. Note that they are declared in two statements. Since these two variables have the same type, they can be declared on the same line of code:

Int brothers, brides;

When multiple variables are declared in a statement, the names of the variables after the data type must be separated by commas (,). The statement should end with a semicolon. This is a very convenient format, but there is a drawback: each variable is not very effective, because they are all placed on a line of code and cannot be annotated to describe each variable. Therefore, they can be divided into two rows. The statement is as follows:

Int brothers, // Declare a variable called brothers

Brides; // and a variable called brides

Split the statement into two rows to add comments. These annotations are ignored by the compiler, so they are the same as the statements that didn't add the annotations at first. The C statement can be divided into several rows. The semicolon determines the end of the statement, rather than the end of the code line.

Of course, you can also write two declaration statements. It is generally better to define a variable in a statement. Variable declaration is often placed at the beginning of the executable statement of the function, but this is not necessary. Generally, the variable declaration to be used in a piece of code is placed behind the starting bracket.

The following two statements assign values to the two variables 7:

Brothers = 7; // Store 7 in the variable brothers

Brides = 7; // Store 7 in the variable brides

Note that the statements that declare these variables are placed before the preceding statements. If a declaration is omitted, or the declaration statement is put behind it, the program will not compile. Variables do not exist in the code before they are declared. They must always be declared before they are used.

The next statement calls the printf () function. Its first parameter is a control string to display a line of text. This string also contains a specification that specifies how the values of subsequent parameters are interpreted and displayed in the text. The two conversion specifiers % d in this control string will be replaced by the values of the second parameter brides and third parameter brothers of the printf () function respectively:

Printf (% dbrides for % d brothers, brides, brothers );

The conversion specifiers are replaced by the values of brides, the second parameter of printf (), and brothers, the third parameter. The value of brides corresponds to the first % d, the value of the brothers variable corresponds to the second % d. If you change the statement for setting the variable value to the following, it will be clearer:

Brothers = 8; // Store 8 in the variable brothers

Brides = 4; // Store 4 in the variable brides

In this clear example, the printf () statement clearly shows the correspondence between variables and conversion specifiers, because the output is as follows:

4 brides for 8 brothers

To demonstrate that the variable name is case-sensitive, modify the printf () function so that one of the variable names starts with an uppercase letter, as shown below:

// Program 2.3A Using more variables

# Include

Int main (void)

{

Int brothers; // Declare a variable called brothers

Int brides; // and a variable called brides

Brothers = 7; // Store 7 in the variable brothers

Brides = 7; // Store 7 in the variable brides

// Display some output

Printf (% d brides for % d brothers, Brides, brothers );

Return 0;

}

An error message is returned when you compile the program of this version. The compiler interprets brides and Brides as two different variables, so it does not understand the variables because it is not declared. This is a common mistake. As mentioned above, typing and spelling errors are a major cause of errors. Variables must be declared before use; otherwise, the compiler cannot identify the statement as an error.

2.3.1 use of Variables

The previous section describes how to declare and name variables, but this is of little use compared to the knowledge learned in Chapter 1. Next, write another program to use the variable value before generating the output.

Try it out: make a simple calculation

This program uses the value of the variable for simple calculation:

// Program 2.4 Simple calculations

# Include

Int main (void)

{

Int total_pets;

Int cats;

Int dogs;

Int ponies;

Int others;

// Set the number of each kind of pet

Cats = 2;

Dogs = 1;

Ponies = 1;

Others = 46;

// Calculate the total number of pets

Total_pets = cats + dogs + ponies + others;

Printf (We have % d pets in total, total_pets); // Output the result

Return 0;

}

The execution result is as follows:

Wehave 50 pets in total

Code Description

As in the preceding example, all statements in braces have the same indentation, which means these statements are included in the braces. The organization program should follow this method, so that a group of statements located between a pair of braces have the same indentation, making the program easier to understand.

First, define five int-type variables:

Int total_pets;

Int cats;

Int dogs;

Int ponies;

Int others;

Because these variables are used to store the number of animals, they must be integers, so they are declared as int type.

The following four assignment statements are used to specify a specific value for the variable:

Cats = 2;

Dogs = 1;

Ponies = 1;

Others = 46;

Now, the Total_Pets variable has not set a clear value. Its value is calculated using other variables:

Total_pets = cats + dogs + ponies + others;

In this arithmetic statement, the value of each variable is combined to calculate the total number of all pets on the right of the value assignment operator, and then store the sum to the variable Total_Pets on the left of the value assignment operator. This new value replaces the old value stored in the Total_Pets variable.

The printf () Statement displays the value of the Total_Pets variable, that is, the calculation result:

Printf (Wehave % d pets in total, total_pets );

Try changing the value of some pets or adding some pets. Remember to declare them, set values for them, and add them to the Total_Pets variable.

2.3.2 variable Initialization

In the preceding example, each variable is declared using the following statement:

Intcats; // The number of cats as pets

 

 

Use the following statement to set the value of the variable Cats:

Cats = 2;

Set the value of the variable Cats to 2. What is the value of the variable before this statement is executed? It can be any number. The first statement creates the variable Cats, but its value is the value left by the previous program in that memory. The subsequent value assignment statement sets the value of the variable Cats to 2. But it is best to initialize the variable when declaring it. The statement is as follows:

Int Cats = 2;

This statement declares Cat as the int type and sets the initial value to 2. It is generally a good practice to initialize a variable when declaring it. It can avoid suspicion of the initial value. When the program is not operating normally, it helps to track errors. Avoiding the use of junk values when creating variables can reduce the chance of computer crash when a program fails. Random use of junk values may lead to various problems. Therefore, from now on, it is good to initialize variables, even if it is 0.

The above program is the first program that actually did something. It is very simple and only adds a few numbers, but this is a very important step. It is a basic example of arithmetic statements. The following describes some more complex computations.

1. Basic arithmetic operations

In C, the format of arithmetic statements is as follows:

Variable name = arithmetic expression;

The arithmetic expression on the right of the value assignment operator specifies the values stored in the variable and/or clearly given numbers, and arithmetic operators such as plus (+), minus (-), multiplication (*) and divide (/) for calculation. Other operators can also be used in arithmetic expressions, as described later.

The arithmetic statements in the preceding example are as follows:

Total_pets = cats + dogs + ponies + others;

This statement calculates the arithmetic expression on the right of the equal sign, and then saves the result to the variable on the left.

In C, the symbol "=" defines an action, instead of indicating that the two sides are equal as in mathematics. It specifies to save the result of the expression on the right to the variable on the left. Therefore, you can write the following statement:

Total_pets = total_pets + 2;

From a mathematical point of view, it is ridiculous, but it is correct for programming. Suppose you re-compile the program and add the preceding statement. The program segment with this statement added is as follows:

Total_pets = cats + dogs + ponies + others;

Total_pets = total_pets + 2;

Printf (The total number of petsis: % d, total_pets );

After the first statement is executed, the value of Total_Pets is 50. Then, the second line extracts the value of Total_Pets, adds 2 to the value, and stores the result back to the variable Total_Pets. Therefore, the total number shown at the end is 52.

Note:

In the value assignment operation, calculate the expression on the right of the equal sign and save the result to the variable on the left of the equal sign. The new value replaces the original value in the variable on the left of the value assignment operator. The variable on the left of the value assignment operator is called lvalue, because a value can be stored in this position. The value obtained from the expression on the right of the value assignment operator is called rvalue because it is a value obtained from the calculation expression.

The calculation result is a numeric expression called an arithmetic expression. The following are arithmetic expressions:

3 1 + 2 total_pets cats + dogs-ponies-data

When these expressions are calculated, a value is obtained. Note: The variable name is also an expression, and its calculation result is a value, that is, the value contained in the variable. The value in the last example is the negative value of data. Therefore, if data contains-5, the value of expression-data is 5. Of course, the value of data is still-5. We will discuss in detail how to build expressions and learn operation rules later. Here we use basic arithmetic operators for some simple examples. Table 2-1 lists these arithmetic operators.

Table 2-1 Basic Arithmetic Operators

Operator

Animation

+

Add

-

Subtraction

*

Multiplication

/

Division

%

Modulus)

The data items that use operators are generally called operands. When the operands on both sides are integers, all these operators generate integer results. We have not mentioned the modulo operator before. It uses the expression value on the left of the operator to remove the expression value on the right of the operator and obtain the remaining number. This is sometimes called the remainder operator. The result of expression 12% 5 is 2. Because the remainder of 12 divided by 5 is 2. The next section describes in detail. All these operators work in the same way as our common sense. Except division operators, they are not intuitive when applied to integers. Here are some arithmetic operations.

Note:

The value of an application operator is called an operand. Operators that require two operands (for example, %) are called binary operators. An operator applied to a value is called a unary operator. Therefore, the expression a-B is a binary operator and the expression-data is a unary operator.

Try: subtraction and multiplication

The following food-based program demonstrates subtraction and multiplication:

// Program 2.5 Calculations with cookies

# Include

Int main (void)

{

Int cookies = 5;

Int cookie_calories = 125; // Calories per cookie

Int total_eaten = 0; // Total cookies eaten

Int eaten = 2; // Number to be eaten

Cookies = cookies-eaten; // Subtract number eaten fromcookies

Total_eaten = total_eaten + eaten;

Printf (I have eaten % d cookies. There are % d cookies left,

Eaten, cookies );

Eaten = 3; // New value for cookies eaten

Cookies = cookies-eaten; // Subtract number eaten from cookies

Total_eaten = total_eaten + eaten;

Printf (I have eaten % d more. Now there are % d cookiesleft, eaten, cookies );

Printf (Total energy consumed is % dcalories., total_eaten * cookie_calories );

Return 0;

}

This program generates the following output:

I have eaten 2 cookies. There are 3 cookies left

I have eaten 3 more. Now there are 0 cookies left

Total energy consumedis 625 calories.

Code Description

Declare and initialize three int-type variables:

Int cookies = 5;

Int cookie_calories = 125; // Calories per cookie

Int total_eaten = 0; // Total cookies eaten

In the program, use the total_eaten variable to calculate the total number of consumed cookies, so initialize it to 0.

The next declared and initialized variable stores the number of consumed cookies as follows:

Inteaten = 2; // Number to be eaten

Use the subtraction operator to remove eaten from cookies:

Cookies = cookies-eaten; // Subtract number eaten from cookies

The result of the subtraction operation is stored in the cookie variable, so the cookie value is 3. Because you have eaten some cookies, you need to increase the number of biscuits to total_eaten:

Total_eaten = total_eaten + eaten;

Add the current value of the eaten variable 2 to the current value of total_eaten 0. The result is stored back to the total_eaten variable. The printf () statement shows the remaining number of cookies:

Printf (I have eaten % d cookies. There are % d cookies left,

Eaten, cookies );

This statement cannot be placed on a row. Therefore, after the comma after the first parameter of printf (), other content of this statement is placed on the next row. You can split the statement like this to make the program easy to understand or put it within the specified width of the screen. Note that the first string parameter cannot be split in this way. Line breaks cannot be placed between strings. To split a string into two or more rows, each string in one row must have its own pair of double quotation marks. For example, the preceding statement can be written as follows:

Printf (I have eaten % d cookies.

There are % d cookies left,

Eaten, cookies );

If two or more strings are adjacent to each other, the compiler connects them to form a string.

Display the values of eaten and cookies with % d, an integer. In the output string, the eaten value replaces the first % d, and the cookie value replaces the second % d. The string will be wrapped before it is displayed, because there is one at the beginning.

The next statement sets the value of the variable eaten to a new value:

Eaten = 3; // New value for cookies to beeaten

The new value 3 replaces the old value 2 in the eaten variable. Then complete the same operation sequence as before:

Cookies = cookies-eaten; // Subtract numbereaten from cookies

Total_eaten = total_eaten + eaten;

Printf (I have eaten % d more. Now there are % d cookies left, eaten, cookies );

Finally, before executing the return Statement and ending the program, calculate and display the number of calories consumed by the biscuit:

Printf (Totalenergy consumed is % d calories., total_eaten * cookie_calories );

The second parameter of the printf () function is an arithmetic expression rather than a variable. The compiler stores the computing results of the total_eaten * cookie_calories expression in a temporary variable, and then transmits the value to the printf () function as the second parameter. Function parameters can always use arithmetic expressions, as long as the calculation result is of the desired type.

Let's take a look at the division and modulus operators.

Try: division and modulo Operators

Suppose you have a can of biscuits (45 of them) and 7 children. We need to divide the biscuits equally to each child, calculate that each child can get a few cookies, and then divide the remaining several cookies.

// Program 2.6 Cookies and kids

# Include

Int main (void)

{

Int cookies = 45; // Number of cookies in the jar

Int children = 7; // Number of children

Int cookies_per_child = 0; // Number of cookies per child

Int cookies_left_over = 0; // Number of cookiesleft over

// Calculate how many cookies each child gets when they are divided up

Cookies_per_child = cookies/children; // Number of cookies per child

Printf (You have % d children and % d cookies, children, cookies );

Printf (Give each child % d cookies., cookies_per_child );

// Calculate how many cookies are left over

Cookies_left_over = cookies % children;

Printf (There are % d cookies left over., cookies_left_over );

Return 0;

}

Output after executing the program:

You have 7 children and 45 cookies

Give each child 6cookies.

There are 3 cookiesleft over.

Code Description

The following explains the program step by step. The following statement declares and initializes four integer variables: cookies, children, cookies_per_child, and cookies_left_over:

Int cookies = 45; // Number of cookies in the jar

Int children = 7; // Number of children

Int cookies_per_child = 0; // Number of cookies per child

Int cookies_left_over = 0; // Number of cookies left over

Use the Division operator "/" to divide the number of biscuits by the number of children to obtain the number of biscuits for each child:

Cookies_per_child = cookies/children; // Number of cookies per child

The following two statements output the value of the cookie/children variable:

Printf (You have % d children and % dcookies, children, cookies );

Printf (Give each child % dcookies., cookies_per_child );

The output shows that the value of cookies_per_child is 6. This is because when the operand is an integer, the Division operator always obtains an integer. The result of dividing 45 by 7 is 6 and the remainder is 3. The following statement calculates the remainder using a modulo operator:

Cookies_left_over = cookies % children;

The expression on the right of the value assignment operator calculates the remainder of cookies divided by children. Output Remainder of the last statement:

Printf (Thereare % d cookies left over., cookies_left_over );

2. Learn more about Integer Division

When an operand is negative, what is the result of using the division and modulus operators? When performing a division operation, if the operands are different, the result is a negative number. Therefore, expressions-45/7 and 45/-7 have the same results, both of which are-6. If the operands are the same number, they are both positive or negative, and the result is positive. Therefore, both the 45/7 and-45/-7 results are 6. As for the modulus operator, no matter whether the operand is the same number or not, the result is always the same as the symbol of the left operand. Therefore, 45%-7 equals 3,-45/7 equals-3, and-45/-7 equals-3.

3. unary Operators

For example, a multiplication operator is a binary operator. Because it has two operands, the result is one operand multiplied by another. Some operators are unary operators, that is, they only need one operand. More examples will be provided later. But now let's look at one of the most commonly used unary operators.

4. unary minus sign Operator

The preceding operators are binary operators because they all operate on two data items. The C language also has a one-dimensional operator that operates on a data item. The unary minus sign operator is an example. If the operand is negative, it generates a positive result. If the operand is positive, it generates a negative result. To understand the usage of the unary minus sign operator, consider tracking the bank account. Suppose we have saved 200 yuan in the bank. Use two columns in the book to record the income and expenditure of the money, one column to record the expenses paid, and the other column to record the income. The expenditure column is a negative number and the income column is a positive number.

We decided to purchase a CD worth 50 yuan and a book worth 25 yuan. If everything goes well, you will get the balance after you lose 75 yuan from the bank's initial value. Table 2-2 describes the records of these items.

Table 2-2 Income and expenditure records

Item

Inbound

Withdrawal

Remaining amount

Check income

$200

 

$200

CD

 

$50

$150

Books

 

$25

$125

Balance

$200

$75

$125

If you store these numbers in variables, you can enter both the income and expenditure values as positive values. Only when you calculate the balance will these numbers be converted to negative values. Therefore, you can place a negative sign (-) before the variable name.

To output the total expenditure as a negative number, write the following statement:

Int expenditure = 75;

Printf (Your balance has changedby % d.,-expenditure );

This produces the following results:

Yourbalance has changed by-75.

The negative sign indicates that the money is spent, rather than making money. Note that expression-expenditure does not change the value of the expenditure variable, and it is still 75. The value of this expression is-75.

In expression-expenditure, The unary minus sign operator specifies an action, and the result is the sign for turning the expenditure variable: convert a negative number to a positive number and convert a positive number to a negative number. This is different from the negative number operator used to write a negative number (such as-75 or-1.25. In this case, the negative sign does not indicate an action. When a program is executed, no instruction is required. It only tells the compiler to create a negative constant in the program.

 

 

Related Article

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.