酷代码 AI
菜单
服务商

陆凯船长搬箱难题:用 C++ 精准统计合适箱子数量

```cpp #include <iostream> using namespace std; int main() { int n; cin >> n; int weights[10]; for (int i = 0; i < n; i++) { cin >> weights[i]; } int x; cin >> x; int equalCount = 0; int lessCount = 0; for (int i = 0; i < n; i++) { if (weights[i] == x) { equalCount++; } else if (weights[i] < x) { lessCount++; } } cout << equalCount << " " << lessCount; return 0; } ``` 代码解释 1. 输入箱子数量:使用`cin`读取箱子的数量`n`。 2. 输入每个箱子的重量:定义一个长度为10的数组`weights`,使用`for`循环读取每个箱子的重量并存储在数组中。 3. 输入最大能搬动的重量:使用`cin`读取陆凯船长能搬动的最大重量`x`。 4. 统计数量:初始化两个变量`equalCount`和`lessCount`分别用于统计重量刚好和`x`相等的箱子数量以及重量小于`x`的箱子数量。使用`for`循环遍历数组`weights`,如果当前箱子的重量等于`x`,则`equalCount`加1;如果当前箱子的重量小于`x`,则`lessCount`加1。 5. 输出结果:使用`cout`输出`equalCount`和`lessCount`,中间用空格隔开。 ######[AI问答 | 385点数解答 | 2025-12-06 19:12:43]

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