典型算术运算规则:
C++11标准规定,两整数相除,商一律向0取整。
取余:m%(-n)等于m%n,(-m)%n等于-(m%n)
编写程序,使用条件运算符从vector<int>中找到哪些元素是奇数,然后将这些数翻倍
#include<iostream>
#include<vector>
#include<ctime>
#include<cstdlib>
using namespace std;
int main()
{
const int sz = 10; //使用sz作为数组的维度
vector<int> vInt;
srand((unsigned)time(NULL)); //生成随机数的种子
//使用普通for循环为数组赋初始值
cout << "数组的初始值是:" << endl;
for(int i = 0; i < sz; i++)
{
vInt.push_back(rand() % 100); //生成100以内的随机数
cout << vInt[i] << " ";
}
cout << endl;
//使用范围for循环将数组中的奇数翻倍
for(auto &val : vInt)
val = (val % 2 != 0) ? val * 2 : val; //条件表达式
//使用for循环和迭代器输出数组的当前值
cout << "调整后的数组是:" << endl;
for(auto it = vInt.cbegin(); it != vInt.cend(); ++it)
cout << *it << " ";
cout << endl;
return 0;
}
当sizeof()的运算对象是数组名、数组内容、指针时
int x[10];
int *p = x;
cout << sizeof(x)/sizeof(*x) << endl; //10
cout << sizeof(p)/sizeof(*p) << endl; //2
cout << sizeof(p) << endl; //8
小贴士:
//条件运算符的优先级高于逗号运算符
someValue ? ++x,++y : --x,--y;//等价于(someValue ? ++x,++y : --x),--y
利用static_cast执行强制类型转换,对于底层const则使用const_cast