C++ 中不大于 N 的最大偶数字
本教程中,我们将编写一个程序,该程序查找数字之和均为偶数且不大于给定 n 的最大数。
我们来看看解决问题的步骤。
- 初始化数字 n。
- 从 i = n 编写一个循环。
- 检查当前数字的数字之和是否全部为偶数。
- 如果满足上述条件,则打印该数字。
- 否则,递减 i。
示例
我们来看看代码。
#include <bits/stdc++.h> using namespace std; int allDigitsEven(int n) { while (n) { if ((n % 10) % 2){ return 0; } n /= 10; } return 1; } int findLargestEvenNumber(int n) { int i = n; while (true) { if (allDigitsEven(i)) { return i; } i--; } } int main() { int N = 43; cout << findLargestEvenNumber(N) << endl; return 0; }
输出
如果你运行上面的代码,你将得到以下结果。
42
Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.
结论
如果你对教程有任何疑问,可以在评论部分提出。
广告