酷代码 AI
菜单
服务商

C++ 实现旋律类型判断:根据 7 个音符顺序输出升序、降序或混合

以下是实现该功能的 C++ 代码: ```cpp #include <iostream> #include <vector> // 判断旋律类型的函数 std::string judgeMelodyType(const std::vector<int>& notes) { bool isAscending = true; bool isDescending = true; // 检查是否为升序 for (int i = 1; i < notes.size(); ++i) { if (notes[i] < notes[i - 1]) { isAscending = false; break; } } // 检查是否为降序 for (int i = 1; i < notes.size(); ++i) { if (notes[i] > notes[i - 1]) { isDescending = false; break; } } if (isAscending) { return "升序"; } else if (isDescending) { return "降序"; } else { return "混合"; } } int main() { std::vector<int> notes(7); // 读取输入的 7 个音符 for (int i = 0; i < 7; ++i) { std::cin >> notes[i]; } // 调用函数判断旋律类型 std::string result = judgeMelodyType(notes); std::cout << result << std::endl; return 0; } ``` ### 代码解释: 1. **judgeMelodyType 函数**: - 该函数接收一个 `std::vector<int>` 类型的参数 `notes`,表示输入的音符序列。 - 使用两个布尔变量 `isAscending` 和 `isDescending` 分别标记是否为升序和降序。 - 通过遍历音符序列,检查相邻元素的大小关系,判断是否为升序或降序。 - 根据判断结果返回相应的类型。 2. **main 函数**: - 定义一个大小为 7 的 `std::vector<int>` 类型的变量 `notes`,用于存储输入的音符。 - 通过 `std::cin` 读取 7 个音符。 - 调用 `judgeMelodyType` 函数判断旋律类型,并将结果存储在 `result` 变量中。 - 使用 `std::cout` 输出判断结果。 ######[AI问答 | 582点数解答 | 2026-03-21 19:41:16]

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