When I type withdrawal and I put the value higher than the balance if it is not working and blocking this operation

1
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#include <iostream>

std::string nome, menu;
float saldo, valor, saque;
using namespace std;
main()
{
    std::cout << "Digite seu nome: \n";
    std::cin >> nome;
    std::cout << "Digite o saldo: \n";
    std::cin >> saldo;
    std::cout << "Digite o valor: \n";
    std::cin >> valor;
    saque= valor-saldo;

    std::cout << "Digite uma das opcoes (saldo/deposito/retirada):\n";
    std::cin >> menu;

    if (menu == "deposito") {
        saldo = saldo + valor;
        printf("O saldo mais o valor depositado e igual a: %.2f\n", saldo);
    }else if (menu == "retirada") {
            if(saque>=0){
            saldo = saldo - valor;
            printf("O saldo menos o valor depositado e igual a: %.2f\n", saldo);
            }else if(saque<0){
                 printf("Nao foi possivel fazer a retirada, pois o valor que voce retirou e maior que o saldo da conta! \n");
            }
    }else if (menu == "saldo") {
        printf("O saldo e igual a: %.2f\n", saldo);
    }else {
        printf("Erro");
    }
}
    
asked by anonymous 20.04.2018 / 18:31

1 answer

0

The error was precisely that @Sveen already commented. Your calculation of saque is not correct:

saque= valor-saldo;

If you have saldo 100 and valor 50 , your saque will be -50 . For this reason the instruction should be the opposite:

saque = saldo - valor;

And only with this exchange will work as intended. However it is overly complicated, and does not even need this variable saque . It's best to compare directly to if :

}else if (menu == "retirada") {
    if(valor <= saldo){ //<----- compara direto aqui
        saldo -= valor; //<----- atualiza com o operador -= para ser mais curto
        printf("O saldo menos o valor depositado e igual a: %.2f\n", saldo);
    }else { //também já não precisa de else if aqui
        printf("Nao foi possivel fazer a retirada, pois o valor que voce retirou e maior que o saldo da conta! \n");
    }
}

Only valor <= saldo parison already tells you whether withdrawal is valid or not.

See this example working on Ideone

Recommendations:

  • If you always use std:: it does not make sense to keep using namespace std; , and it ends up polluting namespace .
  • Avoid using global variables, just like you did for all you have in the program
  • Keep the declaration of each variable as close as possible to its use instead of declaring everything at the top
21.04.2018 / 01:51