c++:将数字1~256打印为2进制、8进制、16进制格式

《C++ How To Program》上的一道题目(Ex05_18)。做的时候不顺畅,于是看了解答,然后发现自己的代码写得冗长而无用。

答案中用到了流操作符dec,oct,hex,用来输出特定的格式。这是我以前没有碰到的。另外,输出2进制数时的处理方法,很简洁,也值得借鉴。

#include <iostream>
using namespace std;

int main()
{
   int number; // loop counter for binary numbers
   int factor; // current factor for binary numbers

   // use tabs to display table headers
   cout << "Decimal\t\tBinary\t\tOctal\tHexadecimal\n";

   // loop from 1 to 256
   for ( int loop = 1; loop <= 256; loop++ )
   {
      cout << dec << loop << "\t\t";

      // output binary number
      // initialize variables for calculating binary equivalent
      number = loop;
      factor = 256;

      // output first digit
      cout << ( number == 256 ? '1' : '0' );

      // loop until factor is 1, i.e., last digit
      do
      {
         // output current digit
         cout <<
            ( number < factor && number >= ( factor / 2 ) ? '1' : '0' );

         // update factor and number variables
         factor /= 2;
         number %= factor;
      } while ( factor > 1 );

      // output octal number using oct stream manipulator
      cout << '\t' << oct << loop;

      // output hexadecimal number using hex stream manipulator
      cout << '\t' << hex << loop << endl;
   } // end for
} // end main

站长数十年成长感悟,输入暗号查看

桩白墨公众号上还能加入书舟书友群、美团外卖红包群,免费领取站桩和原创 chatgpt 教程哦
暗号:
请关注本站微信公众号,回复“暗号”,即可获取。在微信里搜索“桩白墨”或者“baimoz”或者微信扫描右侧二维码都可以关注站长微信公众号。