十進制整數轉二進制的核心思路是反覆除以 2 取餘數,餘數即為二進制位元(從最低位到最高位),最後逆序輸出。以下是簡潔的 C++ 實作:
#include <iostream>
#include <cmath>
using namespace std;
void Dec_Bin(int num) {
int temp[255], i = 0;
while (num > 0) {
temp[i] = num % 2;
num = floor(num / 2); // 等同 num /= 2
i++;
}
cout << "Bin is:";
while (i > 0) {
cout << temp[i-1];
i--;
}
cout << endl;
}
int main() {
int num;
cout << "Please input a DEC number:";
cin >> num;
Dec_Bin(num);
return 0;
}
floor:整數除法自動截斷,num /= 2 即可,效率更高。std::vector<int> 或 std::string 避免固定陣列大小限制。num & 1 取代 num % 2,num >>= 1 取代除法,現代編譯器通常會自動優化。void Dec_Bin_Optimized(int num) {
if (num == 0) { cout << "Bin is: 0" << endl; return; }
string binary;
bool negative = num < 0;
unsigned int n = negative ? -num : num; // 處理 INT_MIN 需額外小心
while (n) {
binary.push_back('0' + (n & 1));
n >>= 1;
}
if (negative) cout << '-';
reverse(binary.begin(), binary.end());
cout << "Bin is: " << binary << endl;
}