C ++ Handle -0.0 from Database [英] C++ Handle -0.0 from Database

查看:92
本文介绍了C ++ Handle -0.0 from Database的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

目前我正在研究一些C ++代码,我需要从数据库中读取数据,如果数据库值非零,那么我需要应用一些其他逻辑。



但是在数据库中有一些正在计算的值,可以得出-0.0。而这个负零被视为C ++双变量中的垃圾值。我已经在构造函数中将值初始化为0.0。



At present I am working on piece of C++ code in which I need to read data from a database, and if database value is non-zero, then I need to apply some further logic.

But in the database there are values which are being calculated and can come out as -0.0. And this negative zero is being treated as Garbage value in C++ double variable. I have already initialized the value as 0.0 in constructor.

// This list is being populated from Database
for (Sample::List<BalanceSheet>::Iterator i((Sample::List<BalanceSheet> &) Balance.Entries()); i.HaveItem(); ++i) 
{
    if (SomeCondition != "")
    {
        // This is where am getting Garbage values since GetBalance() returns -0.0
        if (i->GetBalance() != 0) 
        {
            DoOperation();
        }
    }
}

推荐答案

这不是关于垃圾收集,而是关于声音编程实践。

双打不是整数 - 显然这会产生微妙的后果。该值实际上不太可能是-0.0,但实际上是一个非常小的负数,可以使用您的调试器显示。这样做可以回答你的问题。



永远不要用这种方式测试双倍:

This is not about garbage collection but about sound programming practices.
Doubles are not integers - while obvious this has subtle consequences. It is unlikely that the value is actually -0.0 but in fact a very small negative number which can be shown using your debugger. Doing this this would have answered the question for you.

Never test a double in this way:
if (i->GetBalance() != 0) // This is a bug waiting to happen

请在此处阅读: https://isocpp.org/wiki/faq/newbie#floating-point-arith [ ^ ]

Read here: https://isocpp.org/wiki/faq/newbie#floating-point-arith[^]


AC / C ++浮点值始终处于已定义状态且永远不会垃圾。由你来处理特殊状态,如NaN(不是数字),无穷大,非规范化数字和带符号的零(是的,负零是有效状态)。要查看您的值是什么,请使用使用printf格式设置最大值的函数将其打印出来。双精度(格式为%。15E)。



但是,从您的应用程序的角度来看,该值可能是垃圾。那么你应该相应地处理这些值。要避免此类值,请确保仅将有效值(从应用程序的角度来看)写入数据库。
A C/C++ floating point value has always a defined state and is never "garbage". It is up to you handle special states like NaN (not a number), infinity, denormalized numbers and signed zeroes (yes, negative zero is a valid state). To see what your value is exactly print it out using a function that uses printf formatting setting the max. precision for doubles (format "%.15E").

However, the value may be "garbage" from the point of view of your application. Then you should handle such values accordingly. To avoid such values, ensure that only valid values (again from the point of view of your application) are written to the database.


这篇关于C ++ Handle -0.0 from Database的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆