酷代码 AI
菜单
服务商
DeepSeek字节豆包
更多选项

小核桃攻击模拟C++实现及素数判断函数

根据您的两个请求,我将分别给出对应的 C++ 代码实现。 ## 🔫 小核桃攻击模拟程序 ```cpp #include <iostream> using namespace std; int main() { int a[5]; for (int i = 0; i < 5; i++) { cin >> a[i]; } int n; cin >> n; for (int t = 0; t < n; t++) { int type; cin >> type; if (type == 1) { // 粒子炮:所有敌人护盾减5 for (int i = 0; i < 5; i++) { a[i] -= 5; } } else if (type == 2) { // 集束粒子炮 int target; cin >> target; target--; // 转换为0-based索引 // 目标敌人护盾减半 a[target] /= 2; // 左边敌人(如果存在) if (target - 1 >= 0) { a[target - 1] /= 2; } // 右边敌人(如果存在) if (target + 1 < 5) { a[target + 1] /= 2; } } // 负数归零 for (int i = 0; i < 5; i++) { if (a[i] < 0) { a[i] = 0; } } } // 输出结果 for (int i = 0; i < 5; i++) { cout << a[i]; if (i < 4) { cout << " "; } } cout << endl; return 0; } ``` ## 🔢 素数判断与输出程序 ```cpp #include <iostream> using namespace std; // 判断一个数是否为素数 bool isPrime(int n) { if (n <= 1) return false; // 1不是素数 for (int i = 2; i * i <= n; i++) { if (n % i == 0) return false; } return true; } int main() { int x; cin >> x; bool first = true; for (int i = 2; i <= x; i++) { if (isPrime(i)) { if (!first) { cout << " "; } cout << i; first = false; } } cout << endl; return 0; } ``` ### 🎯 代码说明 - **isPrime函数**:从2到√n检查是否有因数,时间复杂度O(√n) - **main函数**:遍历2到x,调用isPrime判断后输出,注意空格处理 - **输入10**:输出 `2 3 5 7` ######[AI问答 | 661点数解答 | 2026-07-07 23:16:18]

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