[英]Issue with a math rule of three in c++
我開始學習 c++,但我有一個問題。
我正在嘗試在 c++ 中執行三規則,但我得到了錯誤的結果。 應該給我55.549,38775510204 ,我得到-41842.000000000000
我做錯了什么?? 在 C# 我這樣做並且工作正常:
decimal ruleOfThree = decimal.Divide(decimal.Multiply(32000, 76554), 44100);
在 C++ 我這樣做:
long double ruleOfThree = ((32000 * 76554) / 44100);
只需嘗試您的示例,編譯器就會解釋問題所在:
$ cat test.cpp
#include <iostream>
int main() {
long double ruleOfThree = ((32000 * 76554) / 44100);
std::cout << ruleOfThree << "\n";
return 0;
}
$ g++ test.cpp
test.cpp: In function ‘int main()’:
test.cpp:4:39: warning: integer overflow in expression of type ‘int’ results in ‘-1845239296’ [-Woverflow]
long double ruleOfThree = ((32000 * 76554) / 44100);
~~~~~~^~~~~~~
中間產品被計算為int
並且它溢出。
明確指定要計算的數據類型,它將起作用:
$ cat test.cpp
#include <iostream>
int main() {
long double ruleOfThree = (static_cast<long double>(32000) * 76554) / 44100;
std::cout.precision(17);
std::cout << ruleOfThree << "\n";
return 0;
}
$ g++ test.cpp
$ ./a.out
55549.387755102041
在此處閱讀有關標准促銷和轉換的更多信息: https://docs.microsoft.com/en-us/cpp/cpp/standard-conversions?view=msvc-170
我還沒有在 C++ 編譯器上對此進行測試,但類似於:
long double ruleOfThree = ((32000.0 * 76554.0) / 44100.0);
即確保 3 個乘數是雙倍的,而不是整數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.