我的任务是将十进制数转换为基数p
中的数字。用户输入p
。
到目前为止,这是我的代码:
for(int i = 0; i < 100; i++)
{
if(a % p == 0) nn[i] = '0';
if(a % p == 1) nn[i] = '1';
if(a % p == 2) nn[i] = '2';
if(a % p == 3) nn[i] = '3';
if(a % p == 4) nn[i] = '4';
if(a % p == 5) nn[i] = '5';
if(a % p == 6) nn[i] = '6';
if(a % p == 7) nn[i] = '7';
if(a % p == 8) nn[i] = '8';
if(a % p == 9) nn[i] = '9';
if(a % p == 10) nn[i] = 'A';
if(a % p == 11) nn[i] = 'B';
if(a % p == 12) nn[i] = 'C';
if(a % p == 13) nn[i] = 'D';
if(a % p == 14) nn[i] = 'E';
if(a % p == 15) nn[i] = 'F';
a = a / p;
if(a == 0) break;
}
for(int qq = strlen(nn) - 1; qq >= 0; qq--)
cout << nn[qq];
其中a
是十进制数,char nn
是输出的保存位置。我有这个问题:程序随机输出3个符号和正确的答案。为什么会发生这种情况?如何解决?
答案 0 :(得分:6)
问题是您的nn
字符串仍未终止。在nn[i+1]='\0'
之前设置break
将解决此问题:
if(a==0) {
nn[i+1] = '\0';
break;
}
请注意,您的程序相当不理想:您可以使用字符串文字和索引,而不是设置if
的大链,如下所示:
char *digits = "0123456789ABCDEF";
for(int i=0;i<100;i++) {
nn[i]=digits[a%p];
a=a/p;
if(a==0) {
nn[i+1] = '\0';
break;
}
}
答案 1 :(得分:0)
只要您能找到一个代表数字的符号,这就是我刚才写的可以转换为任何基数的东西:
char* ConvertBaseN(
uint64_t Number,
char* BufArray,
int BufLen,
size_t BaseN) // 0=Maxbase
{
BufArray[0] = '\0';
const char Symbols[] = {
'0', '1', '2', '3', '4', '5','6','7','8','9',
'A', 'B', 'C', 'D', 'E','F','G','H','I','J',
'K','L','M','N','O','P','Q','R','S','T',
'U','V','W','X','Y','Z', 'a', 'b', 'c', 'd', 'e','f','g','h','i',
'j','k','l','m','n','o','p','q','r','s',
't','u','v','w','x','y','z'
};
// Zero means max-base
if (BaseN == 0) {
BaseN = sizeof(Symbols);
}
size_t CharSetIndex;
size_t BufPos = BufLen - 1;
if (BufPos < 1) {
throw("ConvertBaseN: Receive buffer not set"
"big enough to fit converted number");
}
BufArray[BufPos--] = '\0';
do {
if (BufPos == -1) {
throw("ConvertBaseN: Receive buffer not set"
"big enough to fit converted number");
}
CharSetIndex = Number % BaseN;
Number = Number / BaseN;
if (CharSetIndex < 0) {
Number = Number + 1;
CharSetIndex += (BaseN*-1);
}
BufArray[BufPos--] = Symbols[CharSetIndex];
} while (Number != 0);
return BufArray + BufPos + 1;
}