C++ primer(第五版) 练习 4.21 个人code

来源:互联网 发布:西门子plc编程技巧 编辑:程序博客网 时间:2024/05/23 00:02


C++ primer(第五版) 练习 4.21

题目:编写一段程序,使用条件运算符从vector<int>中找到哪些元素的值是奇数,然后将这些奇数值翻倍。

答:

#include <iostream>#include <vector>using std::cout;using std::cin;using std::endl;using std::vector;int main(){vector<int> vt = { 1, 1, 2, 3, 5, 8, 13, 21, 34, 55 };cout << "翻倍前的奇数:" << endl;for (auto a : vt)if (a % 2 != 0){cout << a << " ";}cout << endl << "翻倍后的奇数:" << endl;for (auto &a : vt){if (0 != (a % 2 != 0 ? a * 2 : 0)){cout << (a % 2 != 0 ? a * 2 : 0) << " ";}}return 0;}

执行结果:



0 0