user5750023
user5750023

Reputation:

C++ recognising input value of 0

I'm having a bit of trouble with a piece of code and wanted to ask if I could get some help. Basically I am creating a program that will divide two numbers that are inputted by the user and I want to print a message if either of the inputted numbers are 0 however, this part of the code is not working correctly. Below is the code that I have.

int main()
{


float n1 = 0.0, n2 = 0.0, quotent = 0.0;

int firstNumberRead = 0;

int secondNumberRead = 0;



firstNumberRead = scanf("%f", &n1);

secondNumberRead = scanf("%f", &n2);

//check that the attempt to read the number was successful
if (firstNumberRead && secondNumberRead == 1)
{
    //divide the first number by the second number
    quotent = (n1 / n2);

    //print quotent
    printf("%f", quotent);enter code here
}
else if (firstNumberRead || secondNumberRead == 0)
{
    printf("invalid input - divide by zero is not allowed");
}
else
{
    printf("invalid input");
}
scanf("%f", &n1);
return (0);

}

Upvotes: 0

Views: 69

Answers (1)

krzaq
krzaq

Reputation: 16421

There are numerous problems with this code.

if (firstNumberRead && secondNumberRead == 1)

You're likely mistaken about how conditions work in C++, check your coursebook for a detailed exaplanation. You most likely wanted to say

if(firstNumberRead == 1 && secondNumberRead == 1)

This will only check that both scanf invocations managed to read a value. You need to check the actual value then, inside the if expression.

The other problems was checking incorrect variables for 0 in denominator and numerator (you checked firstNumberRead and secondNumberRead again. You should check n1 and n2 instead:

if (n1 == 0 || n2 == 0)

Usually it's a bad idea to use operator == for floating point variables, but you could argue that it makes sense for the denominator (all other states are legal from arithmetic's point of view). But you might want to look into std::abs and check if it's smaller than some epsilon. For example:

if (abs(n1) < 0.001 || abs(n2) < 0.001)

Finally, you probably want something like this:

if (firstNumberRead == 1 && secondNumberRead == 1)
{
    if (n1 == 0 || n2 == 0)
    {
        printf("invalid input - divide by zero is not allowed");
    }
    else
    {
        //divide the first number by the second number
        quotent = (n1 / n2);

        //print quotent
        printf("%f", quotent);
    }
}
else 
{
    printf("invalid input");
}

Upvotes: 4

Related Questions