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

C++复合赋值运算符(无师自通),第1张

概述程序通常具有以下格式的赋值语句: number = number + 1; 赋值运算符右侧的表达式给 number 加 1,然后将结果赋值给 number,替换先前存储的值。实际上,这个声明给 number 增加了 1。同样的方 程序通常具有以下格式的赋值语句:

number = number + 1;

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

number = number - 5;

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

表 1 更改变量值得赋值语句
语 句 ***  作在执行语句之后 x 的值
x = x + 4;给 x 加 410
x = x-3;从 x 减去 33
x = x * 10;使 x 乘以 1060
x==x/2;使 x 乘以 23
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++复合赋值运算符(无师自通)全部内容,希望文章能够帮你解决C++复合赋值运算符(无师自通)所遇到的程序开发问题。

如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。

欢迎分享,转载请注明来源:内存溢出

原文地址: http://outofmemory.cn/langs/1231327.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-06-06
下一篇 2022-06-06

发表评论

登录后才能评论

评论列表(0条)

保存