TAILIEUCHUNG - Teach Yourself the C# Language in 21 Days phần 3

Bạn đã nhìn thấy rằng varname là tên của biến. giá trị là giá trị đó sẽ được lưu trữ trong biến. Ví dụ, để lưu trữ các số 5, thay đổi my_variable, bạn nhập như sau: my_variable = 5; Giá trị của một biến cũng có thể được thay đổi. Để thay đổi giá trị, bạn chỉ cần gán một giá trị mới: | Controlling Your Program s Flow 137 Listing Using the for Statement 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Using the for statement. print the average of 10 random numbers that are from 1 to 10. - class average public static void Main int ttl 0 variable to store the running total int nbr 0 variable for individual numbers int ctr 0 counter rnd new random number for ctr 1 ctr 10 ctr Get random number nbr int 1 11 Number 0 is 1 ctr nbr ttl nbr add nbr to total nThe total of the 10 numbers is 0 ttl nThe average of the numbers is 0 ttl 10 4 Output Number Number Number Number Number Number Number Number Number Number 1 is 10 2 is 3 3 is 6 4 is 5 5 is 7 6 is 8 7 is 7 8 is 1 9 is 4 10 is 3 The total of the 10 numbers is 54 The average of the numbers is 5 138 Day 4 Analysis Much of this listing is identical to what you saw earlier in today s lessons. You should note the difference however. In Line 15 you see the use of the for statement. The counter is initialized to 1 which makes it easier to display the value in the writeLine routine in Line 20. The condition statement in the for statement is adjusted appropriately as well. What happens when the program flow reaches the for statement Simply put the counter is set to 1. It is then verified against the condition. In this case the counter is less than or equal to 10 so the body of the for statement is executed. When the body in Lines 16-23 is done executing control goes back to the incrementor of the for statement in Line 15. In this for statement s incrementor the counter is incremented by 1. The condition is then checked again and if true the body of the for statement executes again. This continues until the condition fails. For this program this happens when the counter is set to 11. Understanding the for Statement Expressions You can do a lot .

Đã phát hiện trình chặn quảng cáo AdBlock
Trang web này phụ thuộc vào doanh thu từ số lần hiển thị quảng cáo để tồn tại. Vui lòng tắt trình chặn quảng cáo của bạn hoặc tạm dừng tính năng chặn quảng cáo cho trang web này.