0
Why isnt it works properly?
This program should found some variants of A and B, where a+b=a*b #include <iostream> using namespace std; int main() { double a,b,sum,prod; for (a=0.1; a<10; a=a+0.1){ for (b=0.1; b<10; b=b+0.1){ sum=a+b; prod=a*b; if (sum==prod){ cout << a << "*" << b << "=" << a << "+" << b << endl; } } } return 0; }
2 Respostas
+ 2
The answer lies in the precision of the double type.
If you add 0.1 & 0.1, the sum isnt always 0.2
The sum is sometimes something like 0.2000000000000001
If you compare 0.2 with 0.2000000000000001 for equality you get false.
The solution to this problem is to change your if to something like
if (abs(prod - sum) < 0.0000001) // dont forget #include <cmath>
or you can round your prod and sum.
0
So, why isnt it print 2*2=2+2 or 1,5*3=1,5+3?