Base2 到 Base10 转换器不适用于非常大的数字?
Base2 to Base10 converter won't work with very large numbers?
如果用户输入一个非常大的二进制数,输出显示一个0,我该如何修改这个函数来处理更大的数字呢?
{
// Binary to Decimal converter function
int bin_Dec(int myInteger)
{
int output = 0;
for(int index=0; myInteger > 0; index++ )
{
if(myInteger %10 == 1)
{
output += pow(2, index);
}
myInteger /= 10;
}
return output;
}
int _tmain(int argc, _TCHAR* argv[])
{ // start main
int myNumber;
// get number from user
cout << "Enter a binary number, Base2: "; // ask for number
cin >> myNumber;
//print conversion
cout << "Base10: " << bin_Dec(myNumber) << endl; // print conversion
system("pause");
} // end of main
}
停止将您的"二进制数"作为int
。int型在大小上是有限的;最大值一般在20亿左右,也就是10位数。当你把数字当作位滥用时,你得到的最大值是10 位,等于1023。
用string
代替。你没有对输入做任何有用的数学运算;你只是把它当作一串数字。
// oh, and unless you have good reason...this would be better unsigned.
// Otherwise your computer might catch fire when you specify a number larger
// than INT_MAX. With an unsigned int, it's guaranteed to just lop off the
// high bits.
// (I may be overstating the "catch fire" part. But the behavior is undefined.)
unsigned int bin_to_dec(std::string const &n) {
unsigned int result = 0;
for (auto it = n.begin(); it != n.end(); ++it) {
result <<= 1;
if (*it == '1') result |= 1;
}
return result;
}
如果你有c++ 11,有std::stoi
和家族(在<string>
中定义),当你指定基数2时,它们会为你做这些。除非你是为了学习而重新发明轮子,否则最好使用它们。
std::cout << "Base10: " << std::stoi(myNumberString, 0, 2) << 'n';
相关文章:
- 使用浮点数和双精度数的非常小数字的数学
- 如何非常快速地将数字添加到 Vector 中的一系列元素中
- 具有非常非常大数字的算术运算
- 如何在不导致堆栈溢出的情况下计算非常大的数字和很小的 HCF.我正在使用欧几里得算法
- 如何找到由公式计算的非常大的数字的最后一位数字?
- 找到非常大的数字的最右边的未设置位
- 在C++中使用限制和非常大的数字时出现问题
- C 非常奇怪的数字
- 在不使用递归的情况下将 FFT 应用于两个非常大的数字的乘法
- C++整数除法给出非常大的数字
- 在不进行线性搜索的情况下,在非常大的数组中找到比给定数字更小的数字
- 两个非常大的数字的乘积的第一个数字
- 找到非常大数字的分裂模型
- 在非常大的数字序列中查找句点
- 如何在 c++ 中存储非常大的数字
- 查找非常大的 2^n 数字的最后一位数字
- 将十进制转换为二进制,并计算其中的数字非常非常大
- 在GTest中,如何检查数字非常接近0?EXPECT_FLOAT_EQ不工作
- 输出文件中显示的数字非常大
- 数字的组成,其中数字非常大