When I type withdrawal and place the amount higher than the balance the if is not working and barring this operation

Asked

Viewed 37 times

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");
    }
}
  • barring this operation means error? What error? otherwise which result you expected and which is currently returning?

  • 1

    Should not be drawn = balance-value; ?

1 answer

0

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

saque= valor-saldo;

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

saque = saldo - valor;

And only with this exchange will already work as you want. However is complicating excessively, and does not need this variable saque. It is best to compare directly on 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 the comparison valor <= saldo already tells you whether the withdrawal is valid or not.

See this example working on Ideone

Recommendations:

  • Is always used std:: it makes no sense to keep the using namespace std;, and ends up polluting the namespace.
  • Avoid using global variables, as you did for all the variables you have in the program
  • Keep the declaration of each variable as close to your usage as possible instead of declaring everything at the top

Browser other questions tagged

You are not signed in. Login or sign up in order to post.