Error message in c ++

1

These are the methods of my program, when I divide between 0 the error message is printed and then if they print a series of random numbers (I understand the cout of the main is not executed correctly) What is the best way to check that Do not divide between 0?

#include <iostream>
using namespace std;
int dividir(int a, int b) {
    if (b == 0) {
        cout << "ERROR";           
    }
    else {
        return a / b;
    }
} 

int main(){
    int x=3; int y=0;
    cout<<dividir(x,y);
}
    
asked by hugoboss 17.10.2018 в 18:27
source

2 answers

2

As it says @Fran Islands your function does not return any value in case of intent to divide by zero. In most cases, the appropriate thing in C ++ is to cause a exception .

    #include <iostream>
    #include <stdexcept>

    int dividir(int a, int b) {
       if (b == 0) {
          throw std::domain_error( "ERROR: intento de division por cero!");           
       }
       else {
           return a / b;
       }
    } 

    int main(){
       int x=3; int y=0;
       std::cout<<dividir(x,y);
    }

In this example, that is appropriate. For more control you must decide what to do in case of error and program it with a try / catch block. For example:

    int main(){
       int x=3; int y=0;
       try {

       std::cout << dividir(x,y);

       } catch (std::exception& e) {
           std::cout<< e.what();
       } catch (...) {
           std::cout<<"Un error desconocido ha ocurrido!";
       }
    }
    
answered by 17.10.2018 в 20:38
1

Your "divide" function is not returning values in all its flows. I recommend printing the result directly in the function. Being something like this:

#include <iostream>
using namespace std;
 void dividir(int a, int b) {
    if (b == 0) {
        cout << "ERROR";           
    }
    else {
        cout << (a/b);
    }
} 

int main(){
    int x=3; int y=0;
    dividir(x,y);
}

Greetings!

    
answered by 17.10.2018 в 18:53