How to clean screen and re-order data by keyboard in c ++ IF ELSE

0

I am studying c ++, I have the following program, it works but I would like it not to be closed.

//Ficha 4a
/*pregunta dos números, que operación deseas hacer y muestra resultado*/
#include <iostream>
using namespace std;
int main ()

{

double a, b;
int c;

cout << "Introduzca el primer número " << endl ;
cin >> a;
cout << "Introduzca el segundo número" << endl ;
cin >> b;
cout << "Que operación deseas hacer, 1(suma), 2(producto) , 3 (division), 4 (resta)/n" ;
cin >> c;


if (c==1) {
cout <<"el resultado de suma es:"<<a+b<<endl;
}

if (c==2) {
cout <<"el resultado de producto es:"<<a*b<<endl;
}

if (c==3) {
cout <<"el resultado de division es:"<<a/b<<endl;
}

if (c==4) {
cout <<"el resultado de resta es:"<<a-b<<endl;
}


return 0 ;
}
    
asked by Carlos Robayo 05.03.2018 в 19:16
source

3 answers

1

The way is implementing a loop that allows you to enter the data again. In my case I put the options first, since I added the option 5 that means to leave the cycle so that your program finishes. The loop in my example is while (c! = 5) while this condition is true the program will continue running.

//Ficha 4a
/*pregunta dos números, que operación deseas hacer y muestra resultado*/
#include <iostream>
using namespace std;
int main ()

{

double a, b;
int c;

cout << "Que operación deseas hacer, 1(suma), 2(producto) , 3 (division), 4 (resta), 5(salir)/n" ;
cin >> c;

while (c!=5)
{


       cout << "Introduzca el primer número " << endl ;
       cin >> a;
       cout << "Introduzca el segundo número" << endl ;
       cin >> b;

       if (c==1) {
          cout <<"el resultado de suma es:"<<a+b<<endl;
       }

       if (c==2) {
          cout <<"el resultado de producto es:"<<a*b<<endl;
           }

       if (c==3) {
          cout <<"el resultado de division es:"<<a/b<<endl;
         }

      if (c==4) {
          cout <<"el resultado de resta es:"<<a-b<<endl;
        }

cout << "Que operación deseas hacer, 1(suma), 2(producto) , 3 (division), 4 (resta), 5(salir)/n" ;
cin >> c;
}
return 0 ;
}

I leave an example working.

Example

    
answered by 05.03.2018 в 19:43
1

Since you want to repeat the data again, then it is best to use a do-while loop that will guarantee that the data is requested at least once.

On the other hand, the following is half ugly: "Que operación deseas hacer, 1(suma), 2(producto) , 3 (division), 4 (resta)/n" ; besides that at the end it should be \n instead of /n . In these cases it is better to create a menu of options in the following way:

cout << "Que operacion deseas hacer?\n";
cout << "1. Suma\n";
cout << "2. Producto\n";
cout << "3. Division\n";
cout << "4. Resta\n";

In turn, when the user selects an option, we proceed to validate it using another do-while in the following way:

do {
    cout << "Seleccione una de las opciones anteriores:\t";
    cin >> opcion; 

    if (opcion <= 0 || opcion > 4)
        cout << "ERROR. La opcion no existe.\n";
} while (opcion <= 0 || opcion > 4);

By the way, I have changed the variable c , which does not tell me anything, by the variable opcion , since the last one is much clearer in its meaning. Remember that programs must be written as legibly as possible.

Finally, the if is fine ... in principle. Your logic works, but it is always better to do something that is more optimal. In this case, it is better to make use of the selective control structure switch . The syntax is quite simple, every if(...) will become a case .

More concretely, we have the following:

switch(opcion)
{
    case 1: {
        cout << "El resultado de suma es:\t" << num1 + num2 << '\n';
    } break;

    case 2: {
        cout << "El resultado de producto es:\t" << num1 * num2 << '\n';
    } break;

    case 3: {
        cout << "El resultado de division es:\t" << num1 / num2 << '\n'; 
    } break;

    case 4: {
        cout << "El resultado de resta es:\t" << num1 - num2 << '\n';
    } break;            
}

Here I have changed your variables again. In this case a and b for the most descriptive num1 and num2 . We do not need the default because we have previously validated that the options are in the [1-4] range.

This part of my solution may be a bit controversial, since I do not usually use and / or recommend using the system function (which is in the header <cstdlib> ), however, in A little exercise like this, I see nothing wrong. In any case, I recommend you read the following link (in English).

We will use system("cls") that will make the screen clean. Since the process is immediate, it will not give us time to see the result of the chosen operation with our pair of numbers entered. Therefore, before cleaning the screen I use the function Sleep of the header <Windows.h> . This is also not recommended, because it is not multiplatform. As you can deduce from the name, the above only works in Windows. There is a multiplatform way using the function sleep_for of the header <thread> of the C ++ standard, but it is something a little more complicated and I do not want to make your code more complex.

Finally, all the code with the modifications already mentioned:

#include <iostream>
#include <cstdlib>
#include <Windows.h>

using namespace std;

int main ()
{
    double num1, num2;
    int opcion; 

    do {        
        cout << "Introduzca el primer numero:\n";
        cin >> num1;
        cout << "Introduzca el segundo numero:\n";
        cin >> num2;

        cout << "Que operacion deseas hacer?\n";
        cout << "1. Suma\n";
        cout << "2. Producto\n";
        cout << "3. Division\n";
        cout << "4. Resta\n";   

        do {
            cout << "Seleccione una de las opciones anteriores:\t";
            cin >> opcion; 

            if (opcion <= 0 || opcion > 4)
                cout << "ERROR. La opcion no existe.\n";
        } while (opcion <= 0 || opcion > 4);

        switch(opcion)
        {
            case 1: {
                cout << "El resultado de suma es:\t" << num1 + num2 << '\n';
            } break;

            case 2: {
                cout << "El resultado de producto es:\t" << num1 * num2 << '\n';
            } break;

            case 3: {
                cout << "El resultado de division es:\t" << num1 / num2 << '\n'; 
            } break;

            case 4: {
                cout << "El resultado de resta es:\t" << num1 - num2 << '\n';
            } break;            
        }
        Sleep(1000); //Puedes poner otro valor (esta función toma milisegundos)
        system("cls");                          
    } while (opcion != 5);

    return 0;
}

I hope it serves you.

    
answered by 05.03.2018 в 21:04
-1

I did it with the Switch function, I do not know if it is more difficult to understand, since you are studying, if you like to write to my email [email protected]

// Importamos las librerias a utilizar
#include <iostream>
using namespace std;
int main()
{
    // Una variable de tipo entero para poder controlar el switch
    int opc = 0;
    // 3 variables de tipo double, para resultados con puntos decimales
    // n1 - Variable que va a almacenar el digíto 1
    // n1 - Variable que va a almacenar el digíto 2
    // res - Variable que va a almacenar el resultado de la operación
    double n1, n2, res;
    // Ciclo While que controla el menú, así que cuando se precione el número 5 va a terminar el programa
    while(opc != 5)
    {
        // Imprimimos lo que se va a mostrar
        cout<<"Que operacion desea realizar"<<endl;
        cout<<"1. Suma"<<endl;
        cout<<"2. Resta"<<endl;
        cout<<"3. Multiplicacion"<<endl;
        cout<<"4. Division"<<endl;
        cout<<"5. Salir"<<endl;
        // Le decimos al usuario que digité un valor
        cout<<"Ingrese Opcion: ";
        // Guardamos el valor en la variable que va a controlar el elemento switch
        cin>>opc;

        // Condicional que se va a mostrar cada vez que no se digíte un valor deseado
        if(opc > 5)
        {
            cout<<"Ingresa una opcion Valida"<<endl; // Mensaje que se le va a mostrar al usuario
            system("cls"); // Comando para limpiar pantalla
        }

        // Switch que lleva como parametro la variable opc que tiene almacenado el valor ingresado por el ususario
        switch(opc)
        {
            // Si el usuario ingreso el valor 1
            case 1:
                system("cls");
                cout<<"Ingresa el Numero 1: ";
                cin>>n1;
                cout<<"Ingresa el Numero 2: ";
                cin>>n2;
                res = n1 + n2;
                cout<<"El resultado es: "<<res<<endl;
            break; // Palabra reservada que rompe la función que se le estableció y regresa al menú principal

            case 2:
                system("cls");
                cout<<"Ingresa el Numero 1: ";
                cin>>n1;
                cout<<"Ingresa el Numero 2: ";
                cin>>n2;
                res = n1 - n2;
                cout<<"El resultado es: "<<res<<endl;
            break;

            case 3:
                system("cls");
                cout<<"Ingresa el Numero 1: ";
                cin>>n1;
                cout<<"Ingresa el Numero 2: ";
                cin>>n2;
                res = n1 * n2;
                cout<<"El resultado es: "<<res<<endl;
            break;

            case 4:
                system("cls");
                cout<<"Ingresa el Numero 1: ";
                cin>>n1;
                cout<<"Ingresa el Numero 2: ";
                cin>>n2;
                res = n1 / n2;
                cout<<"El resultado es: "<<res<<endl;
            break;

            case 5:
                system("cls");
                cout<<"Gracias por usar el programa :D"<<endl;
                cout<<"\t\tAdios"<<endl;
            break;
        }
    }
    return 0;
}
    
answered by 05.03.2018 в 21:15