<分区>
我应该编写一个可以将十进制数转换为二进制数的程序。我有转换工作的代码,但是当我尝试发送错误时,当用户使用 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;
}