酷代码 AI
菜单
服务商

C++实现二进制转八进制及旋律类型判断

### 💻二进制转八进制代码 ```cpp #include <iostream> #include <string> #include <bitset> #include <sstream> int main() { std::string binary; std::cin >> binary; // 补零,使二进制长度是3的倍数 while (binary.length() % 3 != 0) { binary = "0" + binary; } std::stringstream octalStream; for (int i = 0; i < binary.length(); i += 3) { std::string group = binary.substr(i, 3); std::bitset<3> bits(group); octalStream << bits.to_ulong(); } std::string octal = octalStream.str(); std::cout << octal << std::endl; return 0; } ``` ### 代码解释 1. 首先读取输入的二进制字符串。 2. 为了方便转换,补零使二进制字符串的长度是3的倍数。 3. 按每3位二进制数一组进行处理,将每组转换为对应的八进制数字。 4. 最后将所有转换后的八进制数字拼接输出。 ### 🎵判断旋律类型代码 ```cpp #include <iostream> #include <vector> int main() { std::vector<int> notes(7); for (int i = 0; i < 7; ++i) { std::cin >> notes[i]; } bool isAscending = true; bool isDescending = true; for (int i = 1; i < 7; ++i) { if (notes[i] > notes[i - 1]) { isDescending = false; } if (notes[i] < notes[i - 1]) { isAscending = false; } } if (isAscending) { std::cout << "升序" << std::endl; } else if (isDescending) { std::cout << "降序" << std::endl; } else { std::cout << "混合" << std::endl; } return 0; } ``` ### 代码解释 1. 首先读取7个音符的输入,存储在向量中。 2. 初始化两个布尔变量`isAscending`和`isDescending`为`true`。 3. 遍历音符序列,根据相邻音符的大小关系更新`isAscending`和`isDescending`。 4. 根据`isAscending`和`isDescending`的值输出结果。 ######[AI问答 | 629点数解答 | 2026-03-21 19:50:41]

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