这个貌似是清华大学考研复试题,起初的想法是循环除以2,然后逆序输出,程序也较易实现,不过是否有一种更为便捷的方法呢?
有!包含在<stdlib.h>库里的itoa函数已实现此类功能。源码如下:
#include <iostream>
#include <stdlib.h>
using namespace std;
int main()
{
int nValue=0;
char buf[100]={0};
int n=-1;
int count=0;
memset(buf,0,20*sizeof(char));
cin>>nValue;
cout<<itoa(nValue,buf,2)<<endl;
count=strlen(buf);
for(int i=count-1;i>=0;i--)
{
n++;
if(buf[i]!='0')
{
if(0==i)
{
cout<<"2的"<<count-1<<"次幂="<<nValue<<endl;
}
else
cout<<"2的"<<n<<"次幂+";
}
}
system("pause");
return 0;
}
本文介绍了一种利用C标准库函数itoa将整数转换为二进制字符串的方法,并通过一个示例程序展示了如何输出转换后的二进制表示及其对应的2的幂次形式。
1352

被折叠的 条评论
为什么被折叠?



