3、习题5.14 编写一个程序,输人一个十进制数,输出相应的二进制数。设计一个递归函数实现数制转换。

  • 这代码写的真的是越写越冗长
  • 无力吐槽

#include <iostream>

using namespace std;

void tran_dayu0_b_hex(int x)//转换函数1
{
if (x > 0)
{
static int a[1000];
static int cal = 0;//用于store、计数
int yushu;
yushu = x % 2;
x = x / 2;
a[cal] = yushu;
cal++;
if (x != 0)
{
tran_dayu0_b_hex(x);//调用函数本身
}
else//x=0时结束递归
{
for (int i = cal - 1; i >= 0; i--)
{
cout << a[i];//打印输出二进制
}
}
}
else if (x == 0)
{
cout << "0" << endl;
}

}
void tran_xiaoyu0_b_hex(float x)//转换函数2
{
static int a[1000];
static int cal = 0;//store
x = x * 2;
int j = x;
//float jz
x = x - int(x);
a[cal] = j;
cal++;
if (x==0)//x=0时结束递归
{
//cout << "0.";
for (int i = 0; i <= cal-1 ; i++)
{
cout << a[i];//打印输出二进制
}

}
else
{
tran_xiaoyu0_b_hex(x);//调用函数本身
}

}
void tran_b_hex(float x)//主转换函数
{
if (x>1)
{
if (x - int(x) == 0) //输入的x为大于1的整数
{
int y;
y = x;
tran_dayu0_b_hex(y); //调用转换函数1
}
else //输入一个x为大于1的实数(带小数点)
{
int y;
y = x;
tran_dayu0_b_hex(y);//调用转换函数1
cout << ".";
float m;
m = x - int(x);
tran_xiaoyu0_b_hex(m);//调用转换函数2
}
}
else //输入的x为小于的1的小数
{
cout << "0.";
tran_xiaoyu0_b_hex(x);
}
}
int main()
{
cout << "请输入一个十进制的任意实数" << endl;
float x;
cin >> x;
tran_b_hex(x);//主转换函数
return 0;
}

---yyz

2018.11.4

原文地址:https://www.cnblogs.com/likeghee/p/9906416.html