0

I am trying to write code in C++ for a program that prompts the user for two numbers and finds the sum, difference, product, and quotient. The program should let you know that it cannot divide by zero. This is the code I have so far.

#include <iostream>
using namespace std;

int main() {
    double a; //using double will allow user to input fractions 
    double b; //again using double will allow the user to input fractions
    double sum, diff, prod, quot; //these variables will store the results

    cout << "Enter a number: ";
    cin >> a;
    cout << "Enter another number: ";
    cin >> b;

    //Operations variables
    sum        = a + b;
    diff       = a - b;
    prod       = a * b;


    //Conclusion
    cout << "Sum is: " << sum << endl;
    cout << "difference is: " << diff << endl;
    cout << "product is: " << prod << endl;

    if (b == 0) {
        cout << "quotient is undefined";
    }
    else {
        quot        = a/b;
    }

    cout << "quotient is: " << quot << endl;

    return 0;
}

This code compiles and runs. the only problem I seem to be having is the placement of my if else statement. I have tried multiple locations. The output I get if I let the second number = 0 is as follows

Enter a number: 12
Enter another number: 0
Sum is: 12
difference is: 12
product is: 0
quotient is undefinedquotient is: 0

How do I get it to to just say undefined if b is zero and give the answer if b is not zero.

Cœur
  • 37,241
  • 25
  • 195
  • 267
  • As you have it, the output involving `quot` is always executed. You want it to be conditionally executed. It happens to be the same condition as a previously used condition. – chris Aug 27 '14 at 01:58
  • I think that this would be a good opportunity to learn how to use a step debugger. Even if you don't yet have enough experience to determine where things are going wrong on inspection, if you step through this program in a debugger, it becomes clearly obvious what is happening and why. – jtlim Aug 27 '14 at 04:59

2 Answers2

4

The problem is your last cout should be inside the else block:

cout << "quotient is";
if (b == 0) {
    cout << " undefined";
} else {
    quot = a/b;
    cout << ": " << quot;
}
cout << endl;

As written, your "quotient is: " << quot is executing in every case, but you actually only want it to execute when b == 0 evaluates to false.

nhgrif
  • 61,578
  • 25
  • 134
  • 173
1

Move the last cout into the else block.

Paul Ratazzi
  • 6,289
  • 3
  • 38
  • 50