C++复合赋值运算符(无师自通)
发布时间:2020-12-16 07:38:54 所属栏目:百科 来源:网络整理
导读:程序通常具有以下格式的赋值语句: number = number + 1; 赋值运算符右侧的表达式给 number 加 1,然后将结果赋值给 number,替换先前存储的值。实际上,这个声明给 number 增加了 1。同样的方式,以下语句从 number 中减去 5: number = number - 5; 如果之
程序通常具有以下格式的赋值语句: number = number + 1; 赋值运算符右侧的表达式给 number 加 1,然后将结果赋值给 number,替换先前存储的值。实际上,这个声明给 number 增加了 1。同样的方式,以下语句从 number 中减去 5:number = number - 5; 如果之前从未看过这种类型的语句,则它可能会导致一些初学者理解上的困惑,因为相同的变量名称出现在赋值运算符的两边。表 1 显示了以这种方式编写的语句的其他示例:
由于这些类型的运算在编程中很常见,因此 C++ 提供了一组专门为这些任务而设计的 运算符。表 2 显示了复合赋值运算符,也称为复合运算符。
表 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 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 result * = a + 5; 在该语句中,和 result 相乘的是 a+5 的和。请注意,复合赋值运算符的优先级低于常规算术运算符的优先级。上述语句和以下语句是等效的:result = result *(a + 5); 表 3 显示了使用复合赋值运算符的其他示例。
(编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
相关内容
- c# – 是否可以在Windows应用商店应用中使用Chromium Embed
- c# – 如何为.Net应用程序选择Oracle提供程序?
- C# 网络编程之简易聊天示例
- ruby-on-rails – 如何在Controller RSpec中测试Devise,错误
- quick-cocos2d-x游戏开发——StateMachine状态机
- Oracle别名大小写 -----解决方案
- react.js-01-HelloWorld
- Flash片头loading与MovieClipLoader
- 如何测试依赖于UIUserInterfaceIdiom(ios)的代码
- c# – Linq-to-Entities Left JOIN