首页 > 解决方案 > 在 C++ 中从 double 转换为 int

问题描述

我在将值从 double 转换为 int 时遇到了一些麻烦。我把第十位值为1和2的数字换算后,换算的值实际上是减了1。有人可以帮我解决这个问题吗?

#include <iostream>
#include <cstring>
#include <cmath>

typedef char* BookName;

using namespace std;

class DecimalBookInfo
{
    public:
        DecimalBookInfo(char inName[], double number);

    private:
        BookName name;
        double code;
        bool verifyCode(double number);

};

int main()
{
    char name[] = "TestBook";
    DecimalBookInfo testBook(name, 230.1);
}

DecimalBookInfo::DecimalBookInfo(char inName[], double number)
{
    // initiate new cstring
    name = new char[strlen(inName)];
    strcpy(name, inName);
    
    if (verifyCode(number))
        code = number;
    else
    {
        cout << "Wrong code...\n";
        exit(1);
    }
}

bool DecimalBookInfo::verifyCode(double number)
{
    double areaCode = floor(number);
    cout << areaCode << endl;
    double subCode = ((number - areaCode) * 100.0);

    cout << static_cast<int>(subCode) << endl;

    if (areaCode > 999 || areaCode < 100 || 
    ((subCode - 10) != 0))
    {
        return false;
    }

    return true;
}

结果是:

230 9 密码错误...

所以我不确定为什么会这样。230后面的数字应该是10。谢谢

标签: c++

解决方案


推荐阅读