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

18th Nov 2016, 11:28 AM
Maxikadze
2 Answers
+ 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.
18th Nov 2016, 12:02 PM
Roland
0
So, why isnt it print 2*2=2+2 or 1,5*3=1,5+3?
18th Nov 2016, 11:53 AM
Maxikadze