簡體   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