我應該寫一個程序,可以將十進制數轉換爲二進制。我有用於轉換工作的代碼,但是當用戶使用if/else語句輸入超過最大/最小值的數字(unsigned short)時嘗試發送錯誤。當輸入一個無效數字時,程序跳轉到轉換語句並輸出最大二進制數(如果輸入超過655355)或者從最大值(如果輸入負數)向後倒計數。上溢/下溢問題?
我以爲寫了一切正確。
#include <iostream>
#include <cmath>
#include <climits>
using namespace std;
// This converts the number to binary, it divides the imputed number by two, printing the reminders//
void bin(unsigned short nub)
{
if (nub <=1)
{
cout << nub;
return;
}
unsigned short rem;
rem = nub % 2;
bin(nub/2);
cout << rem;
}
int main()
{
unsigned short dd;
unsigned short bigNumber = pow(2,sizeof(unsigned short)*8)-1;
cout << "\nPlease enter an unsigned short int between 0 and " << bigNumber << ": ";
cin >> dd;
//Should be printed if user imputs a number larger than the data type//
if (dd > bigNumber)
{
cout << "\nThe number is invalid. Please try again.\n\n";
}
//Should be printed if user imputs a negative number//
else if (dd < 0)
{
cout << "\nThe number is invalid. Please try again.\n\n";
}
//Prints the binary number//
else
{
cout << "\nThe Binary version of " << dd << " is ";
bin(dd);
cout << endl << endl;
}
return 0;
}
由於'dd'和'bigNumber'是同一類型,'bigNumber'被設置爲該類型的最大可能值,所以'dd'不能更大,可以嗎? –
看看['bitset :: to_string()'](http://en.cppreference.com/w/cpp/utility/bitset/to_string)。 – user657267
爲什麼不只是使用bitset(http://www.cplusplus.com/reference/bitset/bitset/) –