【问题标题】:C++: Binary to Decimal w/ Appearance of the Conversion ProcessC++:二进制到十进制,带转换过程的外观
【发布时间】:2020-03-01 07:02:59
【问题描述】:

我正在尝试制作一个将二进制转换为十进制但需要显示转​​换过程的程序

输入一个二进制数:10110

1*(2^4) + 1*(2^2) + 1*(2^1)

10110 的十进制等值是:22

但是循环中间的计数器的值却没有减少,导致这个

SAMPLE IMAGE

这是我当前的代码

#include <iostream>
#include <math.h>
#include <string>

using namespace std;

int main()
{
     int bin, dec = 0, remainder, num, base = 1,counter=0,counter2=0, constnum;
     cout << "Enter the binary number: ";
     cin >> num;
     bin = num;
     constnum = num;
     while(bin > 0)
     {
        bin=bin/10;
        counter2++;
     }

     while (num > 0)
     {
        if (num % 10 == 1) {
            cout << " 1*(2^" << counter2 << ") +";
            counter2--; 
            }
         else if(num % 10 == 0) {
            counter2--;
         }
         remainder = num % 10; //get the last digit of the input
         dec = dec + remainder * base;
         base = base * 2;
         num = num / 10;

    }

     cout << "\nThe decimal equivalent of " << constnum << " : " << dec << endl;
     return 0;

}

【问题讨论】:

    标签: c++ binary


    【解决方案1】:

    只需使用一点设置:

    #include <bitset>
    #include <iostream>
    
    int main()
    {
        std::bitset<32> val;
        std::cin >> val;
        std::cout << val.to_ulong() << "\n";
    }
    

    【讨论】:

      【解决方案2】:

      您应该按升序编写过程,而不是后代,这是为了匹配您的算法,它是按升序排列的

      所以,在你最后一段时间,而不是这个:

      if (num % 10 == 1) {
              cout << " 1*(2^" << counter2 << ") +";
              counter2--; 
              }
      else if(num % 10 == 0) {
              counter2--;
           }
      

      你应该这样做:

      if (num % 10 == 1) {
              cout << " 1*(2^" << counter << ") +";
              counter++;
          }
      else if(num % 10 == 0) {
              counter++;
          }
      

      另外,如果你听从我的建议,你可以删除你的第一个 while:

      while(bin > 0)
       {
          bin=bin/10;
          counter2++;
       }
      

      因为不再需要

      【讨论】:

      • 但是输出应该是 1*(2^4) + 1*(2^2) + 1*(2^1) 你的建议它打印出 1*(2^1) + 1*(2^2) + 1*(2^4)
      【解决方案3】:

      如前所述,您正在以不同的顺序计算和显示结果。我建议您存储结果并稍后显示。比如:

      #include <sstream>
      ....
      
      int pos = 0;
      string res;
      while (num > 0) {
          if (num % 10 == 1) {
              stringstream out;
              out << "1*(2^" << pos << ") + ";
      
              res = out.str() + res;
          }
      
          remainder = num % 10; //get the last digit of the input
          dec = dec + remainder * base;
          base = base * 2;
          num = num / 10;
          pos++;
      }
      
      int len = res.length();
      // to remove the last '+'
      if (len >= 3) {
          res = res.substr(0, len - 3);
      }
      
      cout << res;
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2013-05-14
        • 2019-04-09
        • 1970-01-01
        • 1970-01-01
        • 2023-04-11
        相关资源
        最近更新 更多