简体   繁体   English

我怎样才能正常地将双点数转换为整数?

[英]how I can normal a double point number to a int number exacly?

I have a Client program by tcp connection that send data to a server. 我有一个通过TCP连接将数据发送到服务器的客户端程序。 In client I need send a normalized decimal number to server for normalization I Multiplier decimal number to 100,000 then send it to server but I get wrong number in server. 在客户端中,我需要将标准化的十进制数发送到服务器以进行标准化,将十进制数乘以100,000,然后将其发送到服务器,但是服务器中的编号错误。 for example. 例如。

double price;

I set it from Gui to 74.40 我从Gui设置为74.40

cout<<price; ---> 74.40

and when I serial my object I send 当我序列化对象时,我发送

#define Normal 100000
int tmp = price*Normal;
oDest<<tmp;

In wireshrk I see that client sent 7439999. 在wireshhrk中,我看到该客户端发送了7439999。

why this happened? 为什么会这样? how I can pervent this problem? 我该如何解决这个问题?

Don't store anything as a floating point value. 不要将任何内容存储为浮点值。 Use a rational number instead, or use a fixed point value. 请改用有理数,或使用定点值。 Floating point values (like double ) basically "cheat" in order to fix a large range of possible values into a reasonable chunk of memory, and they have to make compromises in order to do so. 浮点值(如double )基本上是“作弊”,以便将较大范围的可能值固定到合理的内存中,并且为此必须做出妥协。

If you are storing a financial value, consider storing pennies or cents or whatever is the smallest denomination. 如果要存储财务价值,请考虑存储几美分或几分钱或最小的面额的东西。

This is due to floating point precision errors. 这是由于浮点精度错误。 You can add some rounding: 您可以添加一些舍入:

int tmp = (price + 0.5/Normal)*Normal;

由于浮点数无法精确表示十进制数,因此在将其转换为整数时需要四舍五入。

int tmp = price*Normal + 0.5;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查以字符串形式存储的数字(双精度型)在C ++中是否为有效的双精度型? - How can I check if a number (double type) stored as a string is a valid double number in C++? 如何在 C# 中检查给定的双精度数是否正常,即既不是零、次正规、无限也不是 NaN - How to check in C# if the given double number is normal, i.e. is neither zero, subnormal, infinite, nor NaN 在一定位数处截断双浮点 - Truncating a double floating point at a certain number of digits 将int 128除数提高到浮点数 - boost int 128 division to floating point number 如何计算云中每个点的法线 - How can I compute a normal for each point in cloud 在C ++中,如何根据双值概率生成随机数? - In C++, How Can I Generate A Random Number Based Off Of A Double Value Probability? 如果实数可以用double精确表示,我怎么能写一个C ++函数返回true? - How can I write a C++ function returning true if a real number is exactly representable with a double? 如何在C ++中编写一个带有可变数量的double向量的函数? - How can I write a function in C++ that takes variable number of vectors of double? 如何将 64 位浮点数添加到特定索引处的 unsigned char 数组(C++) - How can I add a 64 bit floating point number to an unsigned char array at specific indexes (C++) Z3 SMT Solver - 如何在 FPA 中提取浮点数的值? - Z3 SMT Solver - How can I extract the value of a floating point number in FPA?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM