-4

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

Leo
  • 11
  • 3
  • 3
    Its doing what you asked, -inf is not 0 so the if goes through. if you wanted it to write no solutions because a == 0 then you should check for that first. (I disagree with the duplicate fwiw) – Borgleader Dec 24 '22 at 21:27
  • 1
    The duplicate is good background information, but not _especially_ directly relevant to this question. – Nathan Pierson Dec 24 '22 at 21:28
  • 2
    The duplicate was "[is floating point math broken?](https://stackoverflow.com/questions/588004/is-floating-point-math-broken)" I have reopened this so the question may be better addressed. – Drew Dormann Dec 24 '22 at 22:15

1 Answers1

0

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;
}
founderio
  • 407
  • 1
  • 3
  • 15