4.4 if Statements with Compound Statements This section describes if s dịch - 4.4 if Statements with Compound Statements This section describes if s Việt làm thế nào để nói

4.4 if Statements with Compound Sta

4.4 if Statements with Compound Statements
This section describes if statements having compound statements after the condition or the keyword else. When the symbol {follows the condition or else, the C
compiler either executes or skips all statements through the matching }.
EXAMPLE 4.12 Suppose you are a biologist studying the growth rate of fruit flies. The if statement
if (pop_today > pop_yesterday) {
growth = pop_today - pop_yesterday;
growth_pct = 100.0 * growth / pop_yesterday;
printf("The growth percentage is %.2f
", growth_pct);
}
computes the population growth from yesterday to today as a percentage of
yesterday’s population. The compound statement after the condition executes only
when today’s population is larger than yesterday’s. The first assignment computes
the increase in the fruit fly population, and the second assignment converts it to a
percentage of the original population, which is displayed.
EXAMPLE 4.13 As manager of a company’s automobile fleet, you keep records of the safety
ratings of the fleet cars. In the ifstatement that follows, the true task makes
a record of an automobile ( auto_id) whose crash test rating index ( ctri) is at
least as low (good) as the cutoff you have established for acceptably safe cars
( MAX_SAFE_CTRI). The false task records an auto whose ctridoes not meet your
standard. In either case, an appropriate message is displayed, and one is added
to the count of safe or unsafe cars. Both the true and false tasks are compound
statements.
if (ctri y) { /* Switch x and y */
2.temp = x; /* Store old x in temp */
3.x = y; /* Store old y in x */
4.y = temp; /* Store old x in y */
5.}
xand yso that the smaller number is in xand the larger number is in y. If the two
numbers are already in the proper order, the compound statement is not executed.
Variables x, y, and tempshould all be the same data type. Although the values of x
and yare being switched, an additional variable, temp, is needed to store a copy of
one of these values.
Table 4.9 traces the execution of this ifstatement when xis 12.5and y is
5.0. The table shows that tempis initially undefined (indicated by ?). Each line of
the table shows the part of the ifstatement that is being executed, followed by its
effect. If any variable gets a new value, its new value is shown on that line. If no new
value is shown, the variable retains its previous value. The last value stored in x is
5.0, and the last value stored in yis 12.5.
The trace in Table 4.9 shows that 5.0and 12.5are correctly stored in x and
ywhen the condition is true. To verify that the ifstatement is correct, you would
need to select other data that cause the condition to evaluate to false. Also, you
should verify that the statement is correct for special situations. For example, what
would happen if xwere equal to y? Would the statement still provide the correct
result? To complete the hand trace, you would need to show that the algorithm
handles this special situation properly.
In tracing each case, you must be careful to execute the statement step-by-step
exactly as the computer would execute it. Often programmers assume how a particular step will be executed and don’t explicitly test each condition and trace each
step. A trace performed in this way is of little value.
TABLE 4.9 Trace of if Statement
Statement Part x y temp Effect
12.5 5.0 ?
if (x > y) { 12.5 > 5.0 is true.
temp = x; 12.5 Store old x in temp .
x = y; 5.0 Store old y in x .
y = temp; 12.5 Store old x in y .
194 Chapter 4 • Selection Structures: If and Switch Statements
EXERCISES FOR SECTION 4.4
Self-Check
1. Insert braces where they are needed so the meaning matches the indentation.
if (x > y)
x = x + 10.0;
printf("x Bigger
");
else
printf("x Smaller
");
printf("y is %.2f
", y);
2. Correct the following ifstatement; assume the indentation is correct.
if (deduct < balance);
balance = balance - deduct;
printf("New balance is %.2f
", balance);
else;
printf("Deduction of %.2f refused.
", deduct);
printf("Would overdraw account.
");
printf("Deduction = %.2f Final balance = %.2f",
deduct, balance);
3. Revise the style of the following ifstatement to improve its readability.
if (engine_type == 'J') {printf("Jet engine");
speed_category = 1;}
else{printf("Propellers"); speed_category
= 2;}
Programming
1. Write an ifstatement that might be used to compute and display the average of a set of nnumbers whose sum is stored in variable total. This average
should be found only if nis greater than 0; otherwise, an error message should
be displayed.
2. Write an interactive program that contains an ifstatement that may be used
to compute the area of a square ( area side
2
) or a circle ( area p radius
2
)
after prompting the user to type the first character of the figure name (S or C)
0/5000
Từ: -
Sang: -
Kết quả (Việt) 1: [Sao chép]
Sao chép!
4.4 nếu báo cáo với hợp chất phát biểu Phần này mô tả nếu báo cáo có hợp chất phát biểu sau khi điều kiện hoặc từ khóa khác. Khi biểu tượng {theo các điều kiện hoặc người nào khác, C trình biên dịch thực hiện hoặc bỏ qua các báo cáo tất cả thông qua các kết hợp}. Ví dụ 4.12 giả sử bạn là một nhà sinh học nghiên cứu tốc độ tăng trưởng của ruồi. Nếu tuyên bố Nếu (pop_today > pop_yesterday) {} tăng trưởng = pop_today – pop_yesterday; growth_pct = 100.0 * tăng trưởng / pop_yesterday; printf ("tỷ lệ phần trăm tăng trưởng là %.2f
", growth_pct); } tính tăng dân số từ hôm qua đến ngày hôm nay theo tỷ lệ dân số của ngày hôm qua. Tuyên bố hợp chất sau khi các điều kiện thực hiện chỉ Khi dân số ngày nay là lớn hơn của ngày hôm qua. Nhiệm vụ đầu tiên tính sự gia tăng dân số bay trái cây, và hợp đồng thứ hai chuyển đổi nó để một tỷ lệ phần trăm của dân số ban đầu, mà sẽ được hiển thị. Ví dụ 4,13 là quản lý của một công ty ô tô hạm đội, bạn giữ hồ sơ về sự an toàn Xếp hạng của những chiếc xe hạm đội. Trong ifstatement sau đó, nhiệm vụ thực sự làm cho một kỷ lục của một ô tô (auto_id) có tai nạn thử nghiệm đánh giá index (ctri) là lúc ít nhất là thấp (tốt) như cutoff, bạn đã thiết lập cho acceptably an toàn xe ô tô (MAX_SAFE_CTRI). Việc giả ghi lại một tự động ctridoes mà không đáp ứng của bạn tiêu chuẩn. Trong cả hai trường hợp, một thông báo thích hợp sẽ được hiển thị, và một được thêm vào để tính an toàn hoặc không an toàn xe ô tô. Cả hai nhiệm vụ true và false là hợp chất báo cáo. Nếu (ctri < = MAX_SAFE_CTRI) {} printf ("Xe hơi #% d: safe
", auto_id); an toàn = Két an toàn + 1; } {} khác printf ("Xe hơi #% d: unsafe
", auto_id); không an toàn = không an toàn + 1; } 192 chương 4 • lựa chọn cấu trúc: nếu và chuyển đổi báo cáoNếu bạn bỏ qua niềng răng kèm theo những điều khoản hợp chất, các nếu tuyên bố nào kết thúc sau khi printfcall đầu tiên. Việc chuyển nhượng để safewould được dịch như là một tuyên bố vô điều kiện (luôn luôn bị hành quyết), và trình biên dịch sẽ đánh dấu các từ khóa elseas lỗi bởi vì một tuyên bố không thể bắt đầu với khác. Chương trình phong cách viết nếu báo cáo với hợp chất đúng hoặc lời khai saiChúng tôi kèm theo một tuyên bố hợp chất đó là một nhiệm vụ đúng hoặc một công việc sai trong niềng răng. Các vị trí của các niềng răng là một vấn đề của sở thích cá nhân. Chúng tôi sử dụng mẫu Hiển thị trong ví dụ 4,13. Một số lập trình viên muốn gõ mỗi đôi trên dòng riêng của nó và để sắp xếp các niềng răng: Nếu (điều kiện){ đúng nhiệm vụ } khác { nhiệm vụ sai } Một số lập trình viên muốn sử dụng niềng răng xung quanh tất cả các nhiệm vụ true và false cho dù hợp chất hay không, do đó ifstatements tất cả trong một chương trình có một phong cách phù hợp. Chúng tôi khuyên bạn nên đặt cả hai sự thật và các nhiệm vụ sai trong niềng răng nếu một trong hai là một tuyên bố hợp chất. Cho dù phong cách bạn chọn, hãy chắc chắn rằng bạn áp dụng nó một cách nhất quán. Truy tìm một nếu tuyên bố Một bước quan trọng trong chương trình thiết kế là để xác minh rằng một thuật toán hoặc C tuyên bố là Sửa chữa trước khi bạn chi tiêu nhiều thời gian mã hóa hay gỡ lỗi nó. Thường có một số bổ sung giờ chi tiêu trong xác minh sự đúng đắn của một thuật toán tiết kiệm giờ của mã hóa và thử nghiệm thời gian. Một dấu vết bàn tay, kiểm tra ordesk, là một mô phỏng cẩn thận, từng bước trên giấy của làm thế nào máy tính thực hiện thuật toán hoặc tuyên bố. Kết quả mô phỏng này nên cho thấy tác dụng của từng bước thực hiện bằng cách sử dụng dữ liệu đó là tương đối dễ dàng để xử lý bằng tay. Ví dụ 4,14 trong nhiều vấn đề lập trình, bạn phải đặt một cặp giá trị dữ liệu trong bộ nhớ do đó giá trị nhỏ hơn được lưu trữ trong một biến (nói, x) và giá trị lớn hơn trong khác (nói, y). Ifstatement trong hình 4.6 rearranges bất kỳ hai giá trị được lưu trữ trong tay water (bàn kiểm tra) bước-bystep mô phỏng của một thực hiện của thuật toán 193 4.4 • nếu báo cáo với hợp chất phát biểuTìm 4.6 Nếu tuyên bố để đặt hàng x và y1. if (x > y) {/ * chuyển đổi x và y * / 2. temp = x; / * Cửa hàng cũ x trong nhiệt độ * / 3.x = y; / * Cửa hàng cũ y trong x * / 4.y = tạm thời; / * Cửa hàng cũ x trong y * / 5.} yso xand số lượng nhỏ hơn là trong xand số lớn hơn là trong y. Nếu hai Các con số là đã theo thứ tự thích hợp, các tuyên bố hợp chất không được thực hiện. Biến x, y, và tempshould tất cả là cùng dữ liệu loại. Mặc dù các giá trị của xvà yare được chuyển, một biến bổ sung, tạm thời, cần thiết để lưu trữ một bản sao của một trong những giá trị này. 4.9 bảng dấu vết thực hiện ifstatement này khi xis 12.5and y 5,0. bảng này cho thấy rằng tempis ban đầu undefined (chỉ định bởi?). Mỗi dòng bảng này cho thấy một phần của ifstatement mà đang được thực hiện, theo sau là của nó có hiệu lực. Nếu bất kỳ thay đổi được một giá trị mới, giá trị mới của nó được hiển thị trên dòng. Nếu không có mới giá trị được thể hiện, biến vẫn giữ giá trị trước đây của nó. Giá trị cuối cùng lưu trữ trong x 5.0, và giá trị cuối cùng được lưu trữ trong yis 12,5. Dấu vết trong bảng 4.9 cho thấy rằng 5.0and 12.5are một cách chính xác được lưu trữ trong x và ywhen các điều kiện là đúng sự thật. Để xác minh rằng ifstatement là chính xác, bạn sẽ bạn phải chọn các dữ liệu khác gây ra tình trạng đánh giá sai. Ngoài ra, bạn nên xác minh rằng các báo cáo là chính xác cho các tình huống đặc biệt. Ví dụ, những gì sẽ xảy ra nếu xwere bằng y? Nào các tuyên bố vẫn còn cung cấp cho chính xác kết quả? Để hoàn thành bàn tay vết, bạn sẽ cần để cho thấy rằng các thuật toán xử lý tình trạng này đặc biệt đúng. Trong truy tìm mỗi trường hợp, bạn phải cẩn thận để thực hiện các báo cáo từng bước chính xác như máy tính sẽ thực hiện nó. Lập trình thường giả định như thế nào một bước cụ thể sẽ được thực hiện và không rõ ràng kiểm tra mỗi điều kiện và theo dõi mỗi bước. Một dấu vết thực hiện theo cách này là ít giá trị. 4.9 bảng dấu vết của nếu tuyên bố Tuyên bố một phần x y nhiệt độ có hiệu lực 12,5 5.0? Nếu (x > y) {12,5 > 5.0 là đúng sự thật. temp = x; 12,5 cửa hàng cũ x ở tạm thời. x = y; 5.0 cửa hàng cũ y trong x. y = tạm thời; 12,5 lưu trữ cũ x trong y. 194 chương 4 • lựa chọn cấu trúc: nếu và chuyển đổi báo cáo CÁC BÀI TẬP CHO PHẦN 4.4 Tự kiểm tra 1. chèn niềng răng nơi họ là cần thiết để ý nghĩa phù hợp với sự thụt lề. Nếu (x > y) x = x + 10,0; printf ("x Bigger
"); khác printf ("x Smaller
"); printf ("y là %.2f
", y); 2. sửa chữa ifstatement sau đây; giả sử indentation là chính xác. Nếu (khấu trừ < cân bằng); số dư = cân bằng - khấu trừ; printf ("sự cân bằng mới là %.2f
", cân bằng); khác; printf ("khấu trừ của %.2f từ chối.
", khấu trừ); printf ("nào overdraw tài khoản.
"); printf ("khấu trừ = %.2f cuối cùng cân bằng = %.2f", khấu trừ, cân bằng); 3. sửa đổi phong cách của ifstatement sau đây để cải thiện dễ đọc của nó. Nếu (engine_type == 'J') {printf ("động cơ phản lực"); speed_category = 1;} Else{printf("Propellers"); speed_category = 2;} Lập trình 1. viết một ifstatement có thể được sử dụng để tính toán và hiển thị mức trung bình của một tập hợp của nnumbers mà số tiền được lưu trữ trong biến tất cả. Này là nên được tìm thấy chỉ nếu nis lớn hơn 0; Nếu không, một thông báo lỗi nên được hiển thị. 2. viết một chương trình tương tác bao gồm một ifstatement có thể được sử dụng để tính toán diện tích một hình vuông (khu vực bên2) hoặc một vòng tròn (khu vực bán kính p2) sau khi nhắc người dùng phải gõ các ký tự đầu tiên của tên hình (S hoặc C)
đang được dịch, vui lòng đợi..
Kết quả (Việt) 2:[Sao chép]
Sao chép!
4.4 if Statements with Compound Statements
This section describes if statements having compound statements after the condition or the keyword else. When the symbol {follows the condition or else, the C
compiler either executes or skips all statements through the matching }.
EXAMPLE 4.12 Suppose you are a biologist studying the growth rate of fruit flies. The if statement
if (pop_today > pop_yesterday) {
growth = pop_today - pop_yesterday;
growth_pct = 100.0 * growth / pop_yesterday;
printf("The growth percentage is %.2f
", growth_pct);
}
computes the population growth from yesterday to today as a percentage of
yesterday’s population. The compound statement after the condition executes only
when today’s population is larger than yesterday’s. The first assignment computes
the increase in the fruit fly population, and the second assignment converts it to a
percentage of the original population, which is displayed.
EXAMPLE 4.13 As manager of a company’s automobile fleet, you keep records of the safety
ratings of the fleet cars. In the ifstatement that follows, the true task makes
a record of an automobile ( auto_id) whose crash test rating index ( ctri) is at
least as low (good) as the cutoff you have established for acceptably safe cars
( MAX_SAFE_CTRI). The false task records an auto whose ctridoes not meet your
standard. In either case, an appropriate message is displayed, and one is added
to the count of safe or unsafe cars. Both the true and false tasks are compound
statements.
if (ctri <= MAX_SAFE_CTRI) {
printf("Car #%d: safe
", auto_id);
safe = safe + 1;
} else {
printf("Car #%d: unsafe
", auto_id);
unsafe = unsafe + 1;
}
192 Chapter 4 • Selection Structures: If and Switch Statements
If you omit the braces enclosing the compound statements, the if statement would
end after the first printfcall. The assignment to safewould be translated as an
unconditional statement (always executed), and the compiler would mark the keyword elseas an error because a statement cannot begin with else.
Program Style Writing if Statements with Compound True
or False Statements
We enclose a compound statement that is a true task or a false task in braces. The
placement of the braces is a matter of personal preference. We use the form shown
in Example 4.13 . Some programmers prefer to type each brace on its own line and
to align the braces:
if ( condition )
{
true task
}
else
{
false task
}
Some programmers prefer to use braces around all true and false tasks whether
compound or not, so that all ifstatements in a program have a consistent style. We
recommend enclosing both the true and the false tasks in braces if either is a compound statement. Whichever style you choose, make sure you apply it consistently.
Tracing an if Statement
A critical step in program design is to verify that an algorithm or C statement is
correct before you spend extensive time coding or debugging it. Often a few extra
minutes spent in verifying the correctness of an algorithm saves hours of coding and
testing time.
A hand trace, ordesk check, is a careful, step-by-step simulation on paper of
how the computer executes the algorithm or statement. The results of this simulation should show the effect of each step’s execution using data that are relatively
easy to process by hand.
EXAMPLE 4.14 In many programming problems you must order a pair of data values in memory
so that the smaller value is stored in one variable (say, x) and the larger value in
another (say, y). The ifstatement in Fig. 4.6 rearranges any two values stored in
hand trace (desk
check) step-bystep simulation of an
algorithm’s execution
193 4.4 • if Statements with Compound Statements
FIGURE 4.6 if Statement to Order x and y
1.if (x > y) { /* Switch x and y */
2.temp = x; /* Store old x in temp */
3.x = y; /* Store old y in x */
4.y = temp; /* Store old x in y */
5.}
xand yso that the smaller number is in xand the larger number is in y. If the two
numbers are already in the proper order, the compound statement is not executed.
Variables x, y, and tempshould all be the same data type. Although the values of x
and yare being switched, an additional variable, temp, is needed to store a copy of
one of these values.
Table 4.9 traces the execution of this ifstatement when xis 12.5and y is
5.0. The table shows that tempis initially undefined (indicated by ?). Each line of
the table shows the part of the ifstatement that is being executed, followed by its
effect. If any variable gets a new value, its new value is shown on that line. If no new
value is shown, the variable retains its previous value. The last value stored in x is
5.0, and the last value stored in yis 12.5.
The trace in Table 4.9 shows that 5.0and 12.5are correctly stored in x and
ywhen the condition is true. To verify that the ifstatement is correct, you would
need to select other data that cause the condition to evaluate to false. Also, you
should verify that the statement is correct for special situations. For example, what
would happen if xwere equal to y? Would the statement still provide the correct
result? To complete the hand trace, you would need to show that the algorithm
handles this special situation properly.
In tracing each case, you must be careful to execute the statement step-by-step
exactly as the computer would execute it. Often programmers assume how a particular step will be executed and don’t explicitly test each condition and trace each
step. A trace performed in this way is of little value.
TABLE 4.9 Trace of if Statement
Statement Part x y temp Effect
12.5 5.0 ?
if (x > y) { 12.5 > 5.0 is true.
temp = x; 12.5 Store old x in temp .
x = y; 5.0 Store old y in x .
y = temp; 12.5 Store old x in y .
194 Chapter 4 • Selection Structures: If and Switch Statements
EXERCISES FOR SECTION 4.4
Self-Check
1. Insert braces where they are needed so the meaning matches the indentation.
if (x > y)
x = x + 10.0;
printf("x Bigger
");
else
printf("x Smaller
");
printf("y is %.2f
", y);
2. Correct the following ifstatement; assume the indentation is correct.
if (deduct < balance);
balance = balance - deduct;
printf("New balance is %.2f
", balance);
else;
printf("Deduction of %.2f refused.
", deduct);
printf("Would overdraw account.
");
printf("Deduction = %.2f Final balance = %.2f",
deduct, balance);
3. Revise the style of the following ifstatement to improve its readability.
if (engine_type == 'J') {printf("Jet engine");
speed_category = 1;}
else{printf("Propellers"); speed_category
= 2;}
Programming
1. Write an ifstatement that might be used to compute and display the average of a set of nnumbers whose sum is stored in variable total. This average
should be found only if nis greater than 0; otherwise, an error message should
be displayed.
2. Write an interactive program that contains an ifstatement that may be used
to compute the area of a square ( area side
2
) or a circle ( area p radius
2
)
after prompting the user to type the first character of the figure name (S or C)
đang được dịch, vui lòng đợi..
 
Các ngôn ngữ khác
Hỗ trợ công cụ dịch thuật: Albania, Amharic, Anh, Armenia, Azerbaijan, Ba Lan, Ba Tư, Bantu, Basque, Belarus, Bengal, Bosnia, Bulgaria, Bồ Đào Nha, Catalan, Cebuano, Chichewa, Corsi, Creole (Haiti), Croatia, Do Thái, Estonia, Filipino, Frisia, Gael Scotland, Galicia, George, Gujarat, Hausa, Hawaii, Hindi, Hmong, Hungary, Hy Lạp, Hà Lan, Hà Lan (Nam Phi), Hàn, Iceland, Igbo, Ireland, Java, Kannada, Kazakh, Khmer, Kinyarwanda, Klingon, Kurd, Kyrgyz, Latinh, Latvia, Litva, Luxembourg, Lào, Macedonia, Malagasy, Malayalam, Malta, Maori, Marathi, Myanmar, Mã Lai, Mông Cổ, Na Uy, Nepal, Nga, Nhật, Odia (Oriya), Pashto, Pháp, Phát hiện ngôn ngữ, Phần Lan, Punjab, Quốc tế ngữ, Rumani, Samoa, Serbia, Sesotho, Shona, Sindhi, Sinhala, Slovak, Slovenia, Somali, Sunda, Swahili, Séc, Tajik, Tamil, Tatar, Telugu, Thái, Thổ Nhĩ Kỳ, Thụy Điển, Tiếng Indonesia, Tiếng Ý, Trung, Trung (Phồn thể), Turkmen, Tây Ban Nha, Ukraina, Urdu, Uyghur, Uzbek, Việt, Xứ Wales, Yiddish, Yoruba, Zulu, Đan Mạch, Đức, Ả Rập, dịch ngôn ngữ.

Copyright ©2024 I Love Translation. All reserved.

E-mail: