简体   繁体   中英

Issue with a math rule of three in c++

I started learning c++, but I have an issue.

I'm trying to do a rule of three in c++ but I get a wrong result. Should give me 55.549,38775510204 , and I get -41842.000000000000

What I'm doing wrong?? In C# I do this and works fine:

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

In C++ I'm doing this:

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.

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

I haven't tested this on a C++ compiler, but something like:

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

Ie make sure the 3 multipliers are doubles, not integers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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