The question is to determine if the equation a*x b=0 has 1 solution, and write it, if it has 0 solutions write no solutions and if it has infinite solutions type infinite solutions
#include <iostream>
using namespace std;
int main()
{
float a,b,x;
cin>>a>>b;
x=-b/a;
if(x!=0)
cout<<x<<endl;
else if(a==0)
cout<<"no solution"<<endl;
else
cout<<"infinite solutions"<<endl;
return 0;
}
Its supposed to write "no solutions" but instead it says -inf
CodePudding user response:
Your checks are in the wrong order. Since you are not specifying your input, my assumption is:
a=0;
b=1; // Or any other number, for that matter
This means, for your input, you are dividing -1
by 0
which is -inf
(Mathematically incorrect, but floating point numbers (sometimes) work that way, see The behaviour of floating point division by zero)
If-else chains are evaluated from top to bottom, stopping at the first condition evaluating to true
.
As you are checking x!=0
first and -inf
is not equal to 0
, you just get the output of -inf
.
To ensure you catch the division by zero case, you need to check for that first.
Your code would look like this then:
#include <iostream>
using namespace std;
int main()
{
float a,b,x;
cin>>a>>b;
x=-b/a;
if(a==0)
cout<<"no solution"<<endl;
else if(x!=0)
cout<<x<<endl;
else
cout<<"infinite solutions"<<endl;
return 0;
}