在 C++ 中使用 while 循环将二进制转换为十进制
我目前正在阅读一本关于 C++ 的书,其中有一项任务要求读者将二进制数(由用户输入)转换为十进制数。到目前为止,我有以下代码,但它所做的只是输出 0。知道出了什么问题吗?
#include <iostream>
using namespace std;
int main()
{
int x, b = 10, decimalValue = 0, d, e, f, count = 1, counter = 0;
cout << "Enter a binary number: ";
cin >> x;
x /= 10;
while( x > 0)
{
count++;
x = x/10;
}
while (counter < count)
{
if (x == 1)
{
f = 1;
}
else{
f = x % b;
}
if (f != 0)
{
if (counter == 0)
{
decimalValue = 1;
}
else
{
e = 1;
d = 1;
while (d <= counter)
{
e *= 2;
d++;
}
decimalValue += e;
}
}
x /= b;
counter++;
}
cout << decimalValue << endl;
system("pause");
return 0;
}
I am currently reading a book on C++ and there is a task which asks the reader to convert a binary number (inputted by the user) to a decimal equivalent. So far I have the following code, but all it does is output 0. Any idea what has gone wrong?
#include <iostream>
using namespace std;
int main()
{
int x, b = 10, decimalValue = 0, d, e, f, count = 1, counter = 0;
cout << "Enter a binary number: ";
cin >> x;
x /= 10;
while( x > 0)
{
count++;
x = x/10;
}
while (counter < count)
{
if (x == 1)
{
f = 1;
}
else{
f = x % b;
}
if (f != 0)
{
if (counter == 0)
{
decimalValue = 1;
}
else
{
e = 1;
d = 1;
while (d <= counter)
{
e *= 2;
d++;
}
decimalValue += e;
}
}
x /= b;
counter++;
}
cout << decimalValue << endl;
system("pause");
return 0;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
因为
while( x > 0)
循环仅在x <= 0
时停止。此外,cin>> x
让用户输入一个十进制数字。Because the
while( x > 0)
loop only stops whenx <= 0
. Besides,cin >> x
lets the user input a decimal number.在这段代码之后:
x 始终为 0,因此将
x
放入用于计算count
的临时变量中:After that bit of code:
x is always 0, so put
x
into a temporary variable that you use to computecount
:我写了一些示例代码。阅读一下,看看您是否能理解我所做的事情。对任何令人困惑的地方提出问题。
考虑输入“1101”
I've written some sample code. Have a read and see if you can understand what I've done. Ask questions about any bits that are confusing.
Consider an input of "1101"
据我所知,实现此目的的最简单方法如下:
例如,“101”将转换如下:
1) 小数 = (0 << 1) + 1 = 1
2) 小数 = (1 << 1) + 0 = 2
3) 小数 = (2 << 1) + 1 = 5
Simplest way I know of to accomplish this would be the following:
For instance, "101" would be converted as follows:
1) decimal = (0 << 1) + 1 = 1
2) decimal = (1 << 1) + 0 = 2
3) decimal = (2 << 1) + 1 = 5