繁体   English   中英

浮点中的C ++算术运算

[英]C++ arithmetic operations in floating point

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

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

您将看到整数除法,该整数返回整数。

隐式转换规则:

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 ++将结果强制转换为int,这会破坏整个计算

不,在这些情况下,由于两个操作数都是整数,因此您需要明确执行整数除法; 完全没有铸造。

正确的答案是执行浮点除法:

1.0/2

这并不是很多额外的努力来写小数点,是吗?

马丁·约克(Martin York)对正在发生的事情有很好的解释,而詹姆斯·麦克尼利斯James McNellis)为您提供了一个正当的答案,让您知道使用文字时该怎么办。

如果改用int / float / short / etc变量,则可以通过将它们强制内联来解决此问题。 例如

double Average(int *values, int count)
{
    int sum = 0;
    for(int i = 0; i < count; ++i) sum += values[i];
    return sum / (double) count; // Cast one of the values to double, that will force both to be calculated as doubles
    // note that "return (double)sum / count;" won't work because operator precendence
    // causes this to translate to "return (double)(sum / count);"

    // the "c++ way" to do this would be through the static_cast operator
    // i.e. "return static_cast<double>(sum)/count;"
    //  or  "return sum/static_cast<double>(count);"
    // both of which are very explicit in what you are casting
}

暂无
暂无

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM