c++:将数字1~256打印为2进制、8进制、16进制格式
- C/C++
- 2015-05-02
- 126热度
- 0评论
《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