酷代码 AI
菜单
服务商

C++判断桃子喜欢的数字个数及开发优化建议

### 💡思路分析 要解决这个问题,我们需要遍历输入的三个数字,分别获取每个数字的个位,然后判断个位是否为 3、5 或 7。如果是,则计数器加 1。最后输出计数器的值。 ### 📝代码实现 ```cpp #include <iostream> using namespace std; int main() { int a, b, c; // 输入三个数字 cin >> a >> b >> c; int count = 0; // 判断 a 的个位是否为 3、5 或 7 int lastDigitA = a % 10; if (lastDigitA == 3 || lastDigitA == 5 || lastDigitA == 7) { count++; } // 判断 b 的个位是否为 3、5 或 7 int lastDigitB = b % 10; if (lastDigitB == 3 || lastDigitB == 5 || lastDigitB == 7) { count++; } // 判断 c 的个位是否为 3、5 或 7 int lastDigitC = c % 10; if (lastDigitC == 3 || lastDigitC == 5 || lastDigitC == 7) { count++; } // 输出桃子喜欢的数字的个数 cout << count << endl; return 0; } ``` ### ⚙️代码解释 1. **输入部分**:使用 `cin` 读取三个整数 `a`、`b`、`c`。 2. **判断部分**:通过取模运算 `% 10` 分别获取 `a`、`b`、`c` 的个位数字,然后使用 `if` 语句判断个位数字是否为 3、5 或 7。如果是,则将计数器 `count` 加 1。 3. **输出部分**:最后使用 `cout` 输出计数器 `count` 的值,即桃子喜欢的数字的个数。 ### 💻开发建议 - **使用循环优化**:当输入的数字数量较多时,可以使用循环来处理,避免代码的重复。例如,将三个数字存储在数组中,然后使用 `for` 循环遍历数组。 ```cpp #include <iostream> using namespace std; int main() { int numbers[3]; for (int i = 0; i < 3; i++) { cin >> numbers[i]; } int count = 0; for (int i = 0; i < 3; i++) { int lastDigit = numbers[i] % 10; if (lastDigit == 3 || lastDigit == 5 || lastDigit == 7) { count++; } } cout << count << endl; return 0; } ``` - **函数封装**:将判断个位数字是否为 3、5 或 7 的逻辑封装成一个函数,提高代码的复用性。 ```cpp #include <iostream> using namespace std; bool isFavorite(int num) { int lastDigit = num % 10; return lastDigit == 3 || lastDigit == 5 || lastDigit == 7; } int main() { int a, b, c; cin >> a >> b >> c; int count = 0; if (isFavorite(a)) count++; if (isFavorite(b)) count++; if (isFavorite(c)) count++; cout << count << endl; return 0; } ``` ######[AI写代码神器 | 850点数解答 | 2026-02-13 20:11:41]

相关提问
发财导航,免费问AI
实用工具查看更多
Linux在线手册 [开发类]
Jquery在线手册 [开发类]
今日油价 [生活类]
图片互转base64 [开发类]
时间转换器 [开发类]