首页 > 解决方案 > 在类型转换为数据类型时弹出随机值

问题描述

template <class T>
    BOOST_FORCEINLINE bool Decoder::readDecimal(const char* data_ptr, T& input, int &offset, int &size)
    {
        log_.writeln("readDecimal : ", std::string(data_ptr + offset, data_ptr + offset + 10));
        if(offset >= size)
            return false;
        T temp = 0;
        bool decimal = false;
        int mul = 1;
        assert(data_ptr[offset] != '\x01' && data_ptr[offset] != '=');
        for(int i = offset; i < size; i++)
        {
            log_.writeln("readDecimal : ", temp);
            if(data_ptr[i] == '\x01' || data_ptr[i] == '=')
            {
                log_.writeln("readDecimal : ", temp);
                input = temp;
                offset = i + 1;
                return true;
            }
            else if(data_ptr[i] == '.')
            {
                decimal = true;
                continue;
             }
             if(!decimal)
                temp = temp*10 + int(data_ptr[i] - '0');
             else
             {
                log_.writeln("readDecimal : ", temp, " ", int(data_ptr[i] - '0'), " ", T(int(data_ptr[i] - '0')), " ", pow(10,mul), " ", (T(int(data_ptr[i] - '0'))/pow(10,mul)));
                temp = temp + T(int(data_ptr[i] - '0'))/pow(10,mul);
                 mul++;
             }
        }
        return false;
     }

我正在使用上述函数将格式化字符串转换为十进制数据类型(浮点/双精度),但由于某种原因,我看到一些随机值出现在小数位末尾。

基本输入输出:

Input : "19.6"
Output : 19.60000038 (float)

输出日志:

readDecimal : 0.65^A64=20
readDecimal : 0
readDecimal : 0
readDecimal : 0
readDecimal : 0 6 6 10 0.6
readDecimal : 0.6000000238
readDecimal : 0.6000000238 5 5 100 0.05
readDecimal : 0.6500000358
readDecimal : 0.6500000358

另一个例子 :

readDecimal : 19.6^A64=20
readDecimal : 0
readDecimal : 1
readDecimal : 19
readDecimal : 19
readDecimal : 19 6 6 10 0.6
readDecimal : 19.60000038
readDecimal : 19.60000038

函数调用:

decoder.readDecimal<float>(data_ptr, MDIncGrp[index].MDEntryPx, offset, data_size);

标签: c++c++11castingtype-conversiontypecasting-operator

解决方案


推荐阅读