intTypePromotion=1
zunia.vn Tuyển sinh 2024 dành cho Gen-Z zunia.vn zunia.vn
ADSENSE

Using Compound Assignment Operators

Chia sẻ: Nghia Tuan | Ngày: | Loại File: PDF | Số trang:2

75
lượt xem
5
download
 
  Download Vui lòng tải xuống để xem tài liệu đầy đủ

Sử dụng hỗn hợp chuyển nhượng sử dụng Bạn đã thấy cách sử dụng toán tử số học để tạo ra giá trị mới. Ví dụ, báo cáo sau đây sử dụng toán tử + để tạo ra một giá trị là 42 lớn hơn là câu trả lời biến

Chủ đề:
Lưu

Nội dung Text: Using Compound Assignment Operators

  1. Using Compound Assignment Operators You've already seen how to use arithmetic operators to create new values. For example, the following statement uses the + operator to create a value that is 42 greater than the variable answer. The new value is then written to the console: Console.WriteLine(answer + 42); You've also seen how to use assignment statements to change the value of a variable. The following statement uses the assignment operator to change the value of answer to 42: answer = 42; If you want to add 42 to the value of a variable, you can combine the assignment operator and the addition operator. For example, the following statement adds 42 to answer. In other words, after this statement runs, the value of answer is 42 more than it was before: answer = answer + 42; Although this statement works, you'll probably never see an experienced programmer write this. Adding a value to a variable is so common that Microsoft Visual C# lets you perform this task in shorthand manner by using the compound assignment operator, +=. To add 42 to answer, an experienced programmer would write the following statement: answer += 42; You can use this shortcut to combine any arithmetic operator with the assignment operator, as the following table shows. These operators are collectively known as the compound assignment operators. Don't write this Write this variable = variable * number; variable *= number; variable = variable / number; variable /= number; variable = variable % number; variable %= number; variable = variable + number; variable += number; variable = variable - number; variable -= number; TIP The compound assignment operators share the same precedence and right associativity as the simple assignment operator.
  2. The += operator also functions on strings; it appends one string to the end of another. For example, the following code displays “Hello John” on the console: string name = "John"; string greeting = "Hello "; greeting += name; Console.WriteLine(greeting); You cannot use any of the other compound assignment operators on strings. NOTE Use the ++ and -- operators instead of a compound assignment operator when incrementing or decrementing a variable by 1. For example, replace: count += 1; with count++;
ADSENSE

CÓ THỂ BẠN MUỐN DOWNLOAD

 

Đồng bộ tài khoản
2=>2