mardi 12 novembre 2019

I am getting inf when diving a floating point number by 0 and I want instead to say "error"

I am a beginner c++ programmer and this is one of my homework assignments and I got mostly everything done except this one last problem where when the user inputs a number divided by zero it should say "error" but instead I am getting inf as my output. I made an if statement that says if (num1 == 0 || num2 == 0) that it would say error but it is not!

#include <iostream>
#include <iomanip> 
using namespace std;



int main() {

    double num1 {};
    double num2 {};
    char input {};
    double result {};

    cout << "Enter your calculations: ";
    cin >> num1 >> input >> num2;

    cout << fixed << setprecision(2);

    if (input == '+') {
        result = num1 + num2;
    } else if (input == '-') {
        result = num1 - num2;
    } else if (input == '/') {
        result = num1 / num2;
    } else if (input == '*') {
        result = num1 * num2;
    } else if ( num1 == 0 || num2 == 0 ) 
        cout << "error";

     cout << "Answer: "<< result << endl;

    }

Aucun commentaire:

Enregistrer un commentaire