|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
老师让我们写个程序十进制转换二进制,要用到switch 和 case语句,我写了一个运行的很好,但总感觉太繁杂了。请问我这样写有办法化简不?
#include <iostream>
using namespace std;
void binaire(int n, int &n1,int &n2,int &n3,int &n4,int &n5,int &n6,int &n7,int &n8);
int main()
{
int n;
cout<<"n?";
cin >> n;
int n1,n2,n3,n4,n5,n6,n7,n8;
binaire(n,n1,n2,n3,n4,n5,n6,n7,n8);
cout<<n1<<n2<<n3<<n4<<n5<<n6<<n7<<n8<<endl;
}
void binaire(int n, int &n1,int &n2,int &n3,int &n4,int &n5,int &n6,int &n7,int &n8)
{
switch (n%2)
{
case 1:
n8=1;
n/=2;
break;
case 0:
n8=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n7=1;
n/=2;
break;
case 0:
n7=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n6=1;
n/=2;
break;
case 0:
n6=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n5=1;
n/=2;
break;
case 0:
n5=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n4=1;
n/=2;
break;
case 0:
n4=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n3=1;
n/=2;
break;
case 0:
n3=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n2=1;
n/=2;
break;
case 0:
n2=0;
n/=2;
break;
}
switch (n%2)
{
case 1:
n1=1;
n/=2;
break;
case 0:
n1=0;
n/=2;
break;
}
}
好吧,改一下第一个,这次的确有使用switch case 哦,那位老师的本意应该是这个吧 ^_^
#include <iostream>
#include <string>
std::string binaire(uint64_t val, uint8_t length)
{
std::string bin;
uint64_t mask;
switch(length)
{
case sizeof(uint8_t):
mask = 0x80;
break;
case sizeof(uint16_t) :
mask = 0x8000;
break;
case sizeof(uint32_t) :
mask = 0x80000000;
break;
case sizeof(uint64_t) :
mask = 0x8000000000000000;
break;
default:
throw "参数 length 错误!";
}
for( ; mask != 0; mask >>= 1)
{
if(mask & val)
bin.append("1");
else
bin.append("0");
}
return bin;
}
int main(void)
{
uint8_t val8 = 100;
uint16_t val16 = 0xFF00;
uint32_t val32 = 0xAA55AA55;
uint64_t val64 = 0xAA55AA55FFFF0000;
std::cout << binaire(val8, sizeof(val8)) << std::endl;
std::cout << binaire(val16, sizeof(val16)) << std::endl;
std::cout << binaire(val32, sizeof(val32)) << std::endl;
std::cout << binaire(val64, sizeof(val64)) << std::endl;
return 0;
}
|
|