【发布时间】:2021-10-09 15:04:56
【问题描述】:
下面是十进制到十六进制转换的c++程序!!
// decimal to hexadecimal conversion
#include <iostream>
#include <math.h>
#include <string>
using namespace std;
string d2h(int n) {
string s, t;
int i = 0;
while (n >= 1) {
t[i] = n % 16;
switch (t[i]) {
case 10:
t[i] = 'A';
break;
case 11:
t[i] = 'B';
break;
case 12:
t[i] = 'C';
break;
case 13:
t[i] = 'D';
break;
case 14:
t[i] = 'E';
break;
case 15:
t[i] = 'F';
break;
default:
break;
}
s[i] = t[i];
n /= 16;
i++;
}
return s;
}
int main() {
int n;
cin >> n;
cout << d2h(n);
return 0;
}
我没有得到任何输出!!
PS C:\Users\anmol\Desktop\c++projectwork> g++ .\dec2hexadec.cpp
PS C:\Users\anmol\Desktop\c++projectwork> ./a
479
PS C:\Users\anmol\Desktop\c++projectwork>
我应该改变什么??
【问题讨论】:
-
您的字符串
t为空,如果不先增加其大小,您将无法使用t[i] = n % 16;或任何其他t[i] =语句。 -
由于
t是一个空字符串,t[i]通过访问超出范围的索引表现出未定义的行为,对于i的任何值
标签: c++ visual-studio