Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C#

Toán tử tăng/giảm (Increment/Decrement) trong C#

Toán tử tăng (++) tăng giá trị nguyên lên 1:

int a = 10;
a++;
++a;

Toán tử giảm (--) giảm giá trị nguyên xuống 1:

int a = 20;
a--;
--a;

Ví dụ toán tử tăng:

Ví dụ

using System;

class Program {
    static void Main() {
        int a, b;
        a = 10;
        Console.WriteLine(++a); // 11
        Console.WriteLine(a++); // 11
        b = a;
        Console.WriteLine(a);   // 12
        Console.WriteLine(b);   // 12
    }
}

Kết quả

11
11
12
12

Ví dụ toán tử giảm:

int a, b;
a = 10;
Console.WriteLine(--a); // 9
Console.WriteLine(a--); // 9
b = a;
Console.WriteLine(a);   // 8
Console.WriteLine(b);   // 8