number = number + 1;
賦值運算子右側的表示式給 number 加 1,然後將結果賦值給 number,替換先前儲存的值。實際上,這個宣告給 number 增加了 1。同樣的方式,以下語句從 number 中減去 5:number = number - 5;
如果之前從未看過這種型別的語句,則它可能會導致一些初學者理解上的困惑,因為相同的變數名稱出現在賦值運算子的兩邊。表 1 顯示了以這種方式編寫的語句的其他範例:語 句 | 操 作 | 在執行語句之後 x 的值 |
---|---|---|
x = x + 4; | 給 x 加 4 | 10 |
x = x-3; | 從 x 減去 3 | 3 |
x = x * 10; | 使 x 乘以 10 | 60 |
x==x/2; | 使 x 乘以 2 | 3 |
x = x % 4 | 求 x/4 的餘數 | 2 |
運算子 | 用法範例 | 等價表示式 |
---|---|---|
+= | x += 5; | x = x + 5; |
-= | y -= 2; | y = y - 2; |
*= | z *= 10; | z = z * 10; |
/= | a /= b; | a = a / b; |
%= | c %= 3; | c = c % 3; |
//This program tracks the inventory of two widget stores. // It illustrates the use of multiple and combined assignment. #include <iostream> using namespace std; int main() { int beglnv, // Beginning inventory for both stores sold, // Number of widgets sold store1, // Store 1's inventory store2; // Store 2's inventory // Get the beginning inventory for the two stores cout << "One week ago, 2 new widget stores openedn"; cout << "at the same time with the same beginningn"; cout << "inventory. What was the beginning inventory? "; cin >> beglnv; // Set each store1s inventory store1 = store2 = beglnv; // Get the number of widgets sold at each store cout << "How many widgets has store 1 sold? "; cin >> sold; store1 -= sold; // Adjust store 1's inventory cout << " How many widgets has store 2 sold? "; cin >> sold; store2 -= sold; // Adjust store 2's inventory //Display each store1s current inventory cout << " nThe current inventory of each store: n"; cout << "Store 1: " << store1 << endl; cout << "Store 2: " << store2 << endl; return 0; }程式輸出結果:
One week ago, 2 new widget stores opened at the same time with the same beginning inventory. What was the beginning inventory? 100
How many widgets has store 1 sold? 25
How many widgets has store 2 sold? 15
The current inventory of each store: Store 1: 75
Store 2: 85
result * = a + 5;
在該語句中,和 result 相乘的是 a+5 的和。請注意,複合賦值運算子的優先順序低於常規算術運算子的優先順序。上述語句和以下語句是等效的:result = result *(a + 5);
表 3 顯示了使用複合賦值運算子的其他範例。範例用法 | 等價表示式 |
---|---|
x += b + 5; | x = x + (b + 5); |
y -= a * 2; | y = y - (a * 2); |
z *= 10 - c; | z = z * (10 - c); |
a /= b + c; | a = a / (b + c); |
c %= d - 3; | c = c % (d - 3); |