我编写了将十进制小数转换为等效二进制数的代码。它编译正常,但执行时挂起。此处的代码仅打印二进制转换的前四位数字,如果该数字超过4位,则其后将显示“ ...”。执行时挂起。帮助!
#include <iostream>
using namespace std;
int main()
{
int i, x[10];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<=1)
{
i=1;
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
if (i>4)
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
cout << "...";
}
else
{
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
}
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
第一个障碍是无限的while循环:
假设输入数字= 0.5
没有任何东西可以打破循环。
while (num!=1.000)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
要解决,请考虑一些更改。可能还有其他问题。
x
数组的大小),或者i = 4,因为这是最大输出。浮点数的尾数为23位,可能是因为您为x [i]分配的i大于9。
尝试一下:
//stop when you get four bits
while (i< 5)
原始代码有几个问题:
1对于输入num = .5和类似值(对所有值而言确实如此),循环永远不会结束(dash-o建议的修复方法)
2数组x [10]溢出,具有未定义的行为(Edney)
3挑剔:1不是“分数”,最好检查范围0 <= num <1而不是0 <= num <= 1(另请参见OP打印代码;可以添加1);我们可以将x [4]与0 <= i <= 3
一起使用4字符串也可以使用(PaulMcKenzie)。实际上,“ >>”使用字符串处理来解析和计算二进制等效项,然后通过将二进制乘以2(左屎)和截断小数部分来计算目标位。两种方法都给出正确的相同结果。通过字符串实现,我们需要在运算符“ >>”内部添加实现代码,以解析有效格式的浮点数(小数),例如3.14e-1,.2718、1e-1等。
此代码遵循OP:
#include <iostream>
using namespace std;
int main()
{
int i, x[5];
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num>=0 && num<1)
{
i=1;
while (i<=4)
{
num*=2;
x[i]=num;
num=num-x[i];
i++;
}
cout << "The binary equivalent is 0.";
for (i=1;i<=4;i++)
{
cout << x[i];
}
if (num>0)
cout << "...";
}
else
{
cout << "The number entered is out of range.";
}
return 0;
}
此代码没有循环(它们在实现位“ >>”的代码中:]
#include <iostream>
#include <bitset>
using namespace std;
int main () {
const int digits = 4;
int fraction;
float num;
cout << "**PROGRAM TO CONVERT DECIMAL FRACTION INTO ITS EQUIVALENT BINARY**\n";
cout << "Enter a fraction in between 0 to 1 for conversion: ";
cin >> num;
if (num >= 0 && num < 1) {
fraction = num = num * pow (2, digits);
cout << "The binary equivalent is 0.";
cout << bitset<digits> (fraction);
if (num - fraction > 0) cout << "...";
}
else cout << "The number entered is out of range.";
}