gpt4 book ai didi

C++ 浮点算术运算

转载 作者:太空宇宙 更新时间:2023-11-04 15:10:14 25 4
gpt4 key购买 nike

在 C++ 中有没有办法让它将每个浮点运算计算为 double ,即使参数是 int?我有一个程序,很多地方都有代码,例如 1/2、5/6。在这些情况下,C++ 将结果转换为 int,这会搞砸整个计算。从金融计算的角度来看,除了“cmath”之外,还有其他库可以包含更高级的功能吗?

最佳答案

在 C(以及 C++)中,所有内置运算符(即 POD)都对相同类型的对象进行操作。因此,如果内置运算符的参数具有不同类型,那么编译器将(通常)隐式转换其中一个(根据明确定义的规则),以便它们相同。运算符的结果也与输入参数的类型相同。

您看到的是返回整数的整数除法。

隐式转换规则:

1) If either value is long double then cast the other to long doubele  (technically only C)
2) If either value is double then cast the other to double
3) If either value is float then cast the other to float
4) If either value is unsi long then cast the other to unsi long
5) If either value is long then cast the other to long
6) If either value is unsi int then cast the other to unsi int
7) Cast both values to int

注意:所有的算术运算都至少在 int 上完成。这意味着如果两个参数都是 (u)short 和/或 char,那么它们都会被转换为 int。

由此我们可以看出,要使操作发生在 double 上,那么代码中至少有一个参数必须是 double 。为此,只需在表达式中添加小数部分即可。

int val = 1.0/2;

// This is equivalent to:

int val = static_cast<int>( 1.0 / static_cast<double>(2));
// Are you not glad the compiler does the implicit cast for you :-)

关于C++ 浮点算术运算,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3305682/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com