如果数字是整数,我如何检查此代码

How do I check in this code if the number is in integer?

本文关键字:检查 代码 何检查 数字 整数 如果      更新时间:2023-10-16

我写了这段代码来检查我在视频中学到的异常,现在我尝试制作整数的立方体,如果输入的数字不是整数,我希望向用户宣布异常。

#include <iostream>
float cube( float x)
{
    char ch;
    std::cin.get(ch);
    if(ch=='.')
        throw "Should be an integrer";
    float cube=x*x*x;
    return cube;
}
int main ()
{
    float x;
    std::cout<<" Enter an integrer : ";
    std::cin>>x;
    float cube_x=cube(x);
    std::cout<<"Cube("<<x<<")="<<cube_x<<std::endl;
    return 0;
}

您可以使用 boost 词法转换,这正是为此目的。它将引发转换失败的异常。Boost经过充分测试,您可以使用它为您进行转换。

这可能看起来像这样:

#include <boost/lexical_cast.hpp>
#include <iostream>

int cube(int x)
{
    return x*x*x;
}
int main()
{
    std::string x;
    std::cout << " Enter an integrer : ";
    std::cin >> x;
    try
    {
        int y = boost::lexical_cast<int>(x);
        int cube_x = cube(y);
        std::cout << "Cube(" << x << ")=" << cube_x << std::endl;
    }
    catch (const boost::bad_lexical_cast &e)
    {
        std::cerr << e.what() << 'n';
    }
    return 0;
}

顺便说一下,如果你的程序只处理整数,你也应该使用类型 int 而不是 float 来处理数字。

将以下内容添加到源代码中:

#include <math.h>       /* round, floor, ceil, trunc */
...
if (x == round(x)) {
   ...
}

解释可以在这里找到: C++参考