[英]Converts Decimal To Hexadecimal In C++
昨天我写了一个将十进制转换为十六进制的程序。
但我没有满足我的代码,因为我认为我的代码需要别的东西。 我想知道这种转换的另一种解决方案。(例如,使用商和余数,使用 function 或其他)
你能帮助我吗?
//我真的很抱歉我的英语水平。
这是我的代码,
#include<iostream>
#include<math.h>
using namespace std;
int main()
{
char ch[17] = "0123456789ABCDEF";
int power,num;
cout << "Enter A Number: ";
cin >> num;
cout << "Hexadecimal Number: ";
//16^1to16^10 but you can find as you want eg-to 16^15...
for(int i=1;i<11;i++)
{
power = pow(16,i);
if(power > num)
{
for(int k=0;k<i;k++) //for hex num//if i=3, there will be two hex
{
power = pow(16,(i-1)-k);
for(int j=15;j>=0;j--)
{
power *= j;
if(power<=num)
{
cout << ch[j];
num = num-power;
break;
}
power = pow(16,(i-1)-k);
}
}
break;
}
}
}
你可以有从十进制到十六进制
std::stringstream ss;
ss<< std::hex << decimal_value; // int decimal_value
std::string res ( ss.str() );
std::cout << res;
从这个主题之前一定要搜索。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.