C++复合赋值运算符(无师自通)

  • 内容
  • 评论
  • 相关

程序通常具有以下格式的赋值语句:

number = number + 1;

赋值运算符右侧的表达式给 number 加 1,然后将结果赋值给 number,替换先前存储的值。实际上,这个声明给 number 增加了 1。同样的方式,以下语句从 number 中减去 5:

number = number - 5;

如果之前从未看过这种类型的语句,则它可能会导致一些初学者理解上的困惑,因为相同的变量名称出现在赋值运算符的两边。表 1 显示了以这种方式编写的语句的其他示例:

表 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

由于这些类型的运算在编程中很常见,因此 C++ 提供了一组专门为这些任务而设计的 运算符。表 2 显示了复合赋值运算符,也称为复合运算符

表 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;

表 2 中的用法示例说明,复合赋值运算符不需要程序员键入变量名称两次。

下面的程序使用了多变量赋值语句和复合赋值运算符:

//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 opened\n";
    cout << "at the same time with the same beginning\n";
    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 显示了使用复合赋值运算符的其他示例。

表 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);

本文标题:C++复合赋值运算符(无师自通)

本文地址:https://www.hosteonscn.com/3691.html

评论

0条评论

发表评论

邮箱地址不会被公开。 必填项已用*标注