酷代码 AI
菜单
服务商

C++ 实现判断小猫能否跳到第 n 棵树

以下是解决该问题的 C++ 代码: ```cpp #include <iostream> #include <vector> // 检查小猫能否跳到第 n 棵树 bool canReachLastTree(const std::vector<int>& heights) { int n = heights.size(); for (int i = 0; i < n - 1; ++i) { // 如果当前树的高度不小于下一棵树的高度,小猫无法跳到下一棵树 if (heights[i] <= heights[i + 1]) { return false; } } // 能顺利遍历到说明可以跳到第 n 棵树 return true; } int main() { int n; std::cout << "请输入树的数量: "; std::cin >> n; std::vector<int> heights(n); std::cout << "请依次输入每棵树的高度: "; for (int i = 0; i < n; ++i) { std::cin >> heights[i]; } if (canReachLastTree(heights)) { std::cout << "yes" << std::endl; } else { std::cout << "no" << std::endl; } return 0; } ``` ### 代码解释: 1. **`canReachLastTree` 函数**: - 该函数接受一个整数向量 `heights`,表示每棵树的高度。 - 通过遍历向量,比较相邻两棵树的高度。如果当前树的高度不小于下一棵树的高度,小猫无法跳到下一棵树,函数返回 `false`。 - 如果能顺利遍历到说明小猫可以跳到第 `n` 棵树,函数返回 `true`。 2. **`main` 函数**: - 首先,从用户输入中获取树的数量 `n`。 - 然后,依次输入每棵树的高度,并存储在向量 `heights` 中。 - 调用 `canReachLastTree` 函数判断小猫能否跳到第 `n` 棵树,并输出相应的结果。 ######[AI问答 | 514点数解答 | 2026-03-07 21:00:47]

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