总结
- 使用 string 对象,==using namespace std;==不能忘
- C++中的数学函数,pow(x,y) = x^y
- 字符串中的字符转化为int 数字
- str[i] - ‘0’
各个进制的转化- int 的 temp(新变量)要赋初值
- 注意在变量使用中,有些中间变量内容的清楚
- 关于调试
- 控制台和打印追踪
- 关于代码在书写过程中的策略
*先将功能模块写出来,可以分不同的文件,分别调试 - Process finished with exit code返回不是 0,说明哪里出了问题
- 关于特判的思路
- 避免前面出现 0,只要写全部为零进行的 break 操作,其余的正常进行
- 输出格式要完全正确
- 数组的顺序,建议在书写代码块之前,对各个功能块进行草稿,调试的过程中
#include <iostream>
#include <math.h>
using namespace std;
//将二进制转化为八进制的转化函数,返回八进制
char convert(string str) {
string string1 = "";
int temp = 0;
for (int i = 2; i >= 0; i--) {
temp += (str[i] - '0') * pow(2, 2 - i);
}
char str2 = '0' + temp;
return str2;
}
//传入十六进制数,切分为 3 个一组的八进制字符串,进而转化
void twoToEight(string str) {
string string1;
string string2 = "";
if (str.length() % 3 == 0) {
for (int i = str.length() - 1; i - 1 >= 0;) {
if (i != 2) {
string1 += str[i - 2];
string1 += str[i - 1];
string1 += str[i];
i -= 3;
string2 += convert(string1);
string1 = "";
} else if (str[0] == '0' && str[1] == '0' && str[2] == '0') {
break;
} else {
string1 += str[i - 2];
string1 += str[i - 1];
string1 += str[i];
i -= 3;
string2 += convert(string1);
string1 = "";
}
}
} else if (str.length() % 3 == 1) {
for (int i = str.length() - 1; i >= 0;) {
if (i != 0) {
string1 += str[i - 2];
string1 += str[i - 1];
string1 += str[i];
i -= 3;
string2 += convert(string1);
string1 = "";
} else if (str[0] == '0') {
break;
} else {
string1 += '0';
string1 += '0';
string1 += str[0];
i -= 3;
string2 += convert(string1);
string1 = "";
}
}
} else if (str.length() % 3 == 2) {
for (int i = str.length() - 1; i >= 0;) {
if (i != 1) {
string1 += str[i - 2];
string1 += str[i - 1];
string1 += str[i];
i -= 3;
string2 += convert(string1);
string1 = "";
} else if (str[0] == '0' && str[1] == '0') {
break;
} else {
string1 += '0';
string1 += str[0];
string1 += str[1];
i -= 3;
string2 += convert(string1);
string1 = "";
}
}
}
for (int j = string2.length() - 1; j >= 0; j--) {
cout << string2[j];
}
cout << endl;
}
//十六进制转化为二进制数
string sixthToTwo(string str) {
string final;
for (int i = 0; i < str.length(); ++i) {
switch (str[i]) {
case '0':
final += "0000";
break;
case '1':
final += "0001";
break;
case '2':
final += "0010";
break;
case '3':
final += "0011";
break;
case '4':
final += "0100";
break;
case '5':
final += "0101";
break;
case '6':
final += "0110";
break;
case '7':
final += "0111";
break;
case '8':
final += "1000";
break;
case '9':
final += "1001";
break;
case 'A':
final += "1010";
break;
case 'B':
final += "1011";
break;
case 'C':
final += "1100";
break;
case 'D':
final += "1101";
break;
case 'E':
final += "1110";
break;
case 'F':
final += "1111";
break;
}
}
return final;
}
int main() {
int n;
string str, string2;
scanf("%d", &n);
for (int i = 0; i < n; ++i) {
cin >> str;
string2 = sixthToTwo(str);
twoToEight(string2);
}
return 0;
}
来源:CSDN
作者:彩虹编程
链接:https://blog.csdn.net/Mac_Jie/article/details/104430818