简体   繁体   English

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

[英]Issue with a math rule of three in c++

I started learning c++, but I have an issue.我开始学习 c++,但我有一个问题。

I'm trying to do a rule of three in c++ but I get a wrong result.我正在尝试在 c++ 中执行三规则,但我得到了错误的结果。 Should give me 55.549,38775510204 , and I get -41842.000000000000应该给我55.549,38775510204 ,我得到-41842.000000000000

What I'm doing wrong??我做错了什么?? In C# I do this and works fine:在 C# 我这样做并且工作正常:

decimal ruleOfThree = decimal.Divide(decimal.Multiply(32000, 76554), 44100);

In C++ I'm doing this:在 C++ 我这样做:

long double ruleOfThree = ((32000 * 76554) / 44100);

Just try your example and compiler explains what is wrong:只需尝试您的示例,编译器就会解释问题所在:

$ 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);
                                 ~~~~~~^~~~~~~

The intermediate product is computed as int and it overflows.中间产品被计算为int并且它溢出。

Explicitly specify your data types to compute this in and it will work:明确指定要计算的数据类型,它将起作用:

$ 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

Read more on standard promotions and conversions here: https://docs.microsoft.com/en-us/cpp/cpp/standard-conversions?view=msvc-170在此处阅读有关标准促销和转换的更多信息: https://docs.microsoft.com/en-us/cpp/cpp/standard-conversions?view=msvc-170

I haven't tested this on a C++ compiler, but something like:我还没有在 C++ 编译器上对此进行测试,但类似于:

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

Ie make sure the 3 multipliers are doubles, not integers.即确保 3 个乘数是双倍的,而不是整数。

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

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