c++ 中数学规则三的问题

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);

我还没有在 C++ 编译器上测试过这个,但是类似于:

long double ruleOfThree = ((32000.0 * 76554.0) / 44100.0);

即确保 3 个乘数是双倍数,而不是整数。

只需尝试您的示例,编译器就会解释错误所在:

$ 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