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);
CodePudding user response:
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
CodePudding user response:
I haven't tested this on a C compiler, but something like:
long double ruleOfThree = ((32000.0 * 76554.0) / 44100.0);
I.e. make sure the 3 multipliers are doubles, not integers.
