在 C++ 中使用 while 循环将二进制转换为十进制

发布于 2024-11-17 23:37:32 字数 958 浏览 2 评论 0原文

我目前正在阅读一本关于 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

风渺 2024-11-24 23:37:32

因为 while( x > 0) 循环仅在 x <= 0 时停止。此外,cin>> x 让用户输入一个十进制数字。

Because the while( x > 0) loop only stops when x <= 0. Besides, cin >> x lets the user input a decimal number.

唱一曲作罢 2024-11-24 23:37:32

在这段代码之后:

while( x > 0)
{
count++;
x = x/10;
}

x 始终为 0,因此将 x 放入用于计算 count 的临时变量中:

int tmp = x;

while(tmp  > 0)
{
   count++;
   tmp  = tmp /10;
}

After that bit of code:

while( x > 0)
{
count++;
x = x/10;
}

x is always 0, so put x into a temporary variable that you use to compute count:

int tmp = x;

while(tmp  > 0)
{
   count++;
   tmp  = tmp /10;
}
时光匆匆的小流年 2024-11-24 23:37:32

我写了一些示例代码。阅读一下,看看您是否能理解我所做的事情。对任何令人困惑的地方提出问题。

#include <iostream>
#include <string>
#include <cassert>
#include <stdexcept>
#include <limits>

unsigned DecodeBinary(const std::string &sBin)
{
    // check for a bad string
    if (sBin.npos != sBin.find_first_not_of("01"))
        throw std::invalid_argument("Badly formed input string");

    // check for overflow
    if (sBin.length() > std::numeric_limits<unsigned>::digits)
    {
        throw std::out_of_range("The binary number is too big to "
                                "convert to an unsigned int");
    }

    // For each binary digit, starting from the least significant digit, 
    // set the appropriate bit if the digit is not '0'
    unsigned nVal = 0;
    unsigned nBit = 0;
    std::string::const_reverse_iterator itr;
    for (itr=sBin.rbegin(); itr!=sBin.rend(); ++itr)
    {
        if (*itr == '1')
            nVal |= (1<<nBit);
        ++nBit;
    }
    return nVal;
}

int main()
{
    try
    {
        std::cout << "Enter a binary number: ";
        std::string sBin;
        std::cin >> sBin;

        unsigned nVal = DecodeBinary(sBin);

        std::cout << "\n" << sBin << " converts to " << nVal << "\n";
        return 0;
    }
    catch (std::exception &e)
    {
        std::cerr << "\n\nException: " << e.what() << "\n";
        return 1;
    }
}

考虑输入“1101”

从最低有效数字开始,索引 0
索引 3 2 1 0
值 1 1 0 1

它是“1”,因此将输出的位 0 设置为 1 (00000001 = 1)。

下一个数字是零,所以什么也不做。
下一个数字是“1”,因此将位 2 设置为 1 (00000101 = 5)
下一个数字是“1”,因此将第 3 位设置为 1 (00001101 = 13)

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.

#include <iostream>
#include <string>
#include <cassert>
#include <stdexcept>
#include <limits>

unsigned DecodeBinary(const std::string &sBin)
{
    // check for a bad string
    if (sBin.npos != sBin.find_first_not_of("01"))
        throw std::invalid_argument("Badly formed input string");

    // check for overflow
    if (sBin.length() > std::numeric_limits<unsigned>::digits)
    {
        throw std::out_of_range("The binary number is too big to "
                                "convert to an unsigned int");
    }

    // For each binary digit, starting from the least significant digit, 
    // set the appropriate bit if the digit is not '0'
    unsigned nVal = 0;
    unsigned nBit = 0;
    std::string::const_reverse_iterator itr;
    for (itr=sBin.rbegin(); itr!=sBin.rend(); ++itr)
    {
        if (*itr == '1')
            nVal |= (1<<nBit);
        ++nBit;
    }
    return nVal;
}

int main()
{
    try
    {
        std::cout << "Enter a binary number: ";
        std::string sBin;
        std::cin >> sBin;

        unsigned nVal = DecodeBinary(sBin);

        std::cout << "\n" << sBin << " converts to " << nVal << "\n";
        return 0;
    }
    catch (std::exception &e)
    {
        std::cerr << "\n\nException: " << e.what() << "\n";
        return 1;
    }
}

Consider an input of "1101"

Start with least significant digit, index 0
Index 3 2 1 0
Value 1 1 0 1

It is a "1" so set bit 0 of the output to be 1 (00000001 = 1).

Next digit is a zero so do nothing.
Next digit is a '1', so set bit 2 to be 1 (00000101 = 5)
Next digit is a '1', so set bit 3 to be 1 (00001101 = 13)

安稳善良 2024-11-24 23:37:32

据我所知,实现此目的的最简单方法如下:

int binaryToInteger(string binary) {
  int decimal = 0;
  for (char x : binary)  {
      decimal = (decimal << 1) + x - '0';
  }
  return decimal;
}

例如,“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:

int binaryToInteger(string binary) {
  int decimal = 0;
  for (char x : binary)  {
      decimal = (decimal << 1) + x - '0';
  }
  return decimal;
}

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

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文