c++ - 溢出/下溢问题?

标签 c++

<分区>

我应该编写一个可以将十进制数转换为二进制数的程序。我有转换工作的代码,但是当我尝试发送错误时,当用户使用 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 使用另一种数据类型,它能够保存大于 65535 的值(例如 unsigned int)。

关于c++ - 溢出/下溢问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24665619/

相关文章:

c++ - 将 QtConcurrent 用于 QImage::fill 时 Unresolved 重载函数类型

c++ - 路径中的 Qt5 转义空间

c++ - 未命名结构的编译器重新排序

c++ - 未指定的模板参数

c++ - GUI 和文本模式 C++ 设计以消除冗余(可选参数?函数重载?)

c++ - 使用 qt 浏览、列出和删除文件

c++ - 将文件组织到文件夹(模块编程)

c++ - OpenGL 3.0 窗口碰撞检测

c++ - 为什么允许在派生类中调用 protected 静态方法?

c++ - OpenCV 数据类型错误