Switch entering the wrong case

2

I'm trying to solve the problem of Uri 1038 using switch , apparently the values are mixing, Item 3 for example multiplying by 2 (5 x 2) returns the value 3. What am I doing wrong here ?

#include "pch.h"
#include <iostream>

using namespace std;

int main()
{
    int i, q;

    float valor;

    cin >> i >> q;

    switch (i) {
        case 1:
            valor = 4.00*q;
        case 2:
            valor = 4.50*q;
        case 3:
            valor = 5.00*q;
        case 4:
            valor = 2.00*q;
        case 5:
            valor = 1.50*q;
    }

    cout << "Total: R$" << valor;
}

    
asked by anonymous 16.08.2018 / 19:30

1 answer

3
The problem in this code is the lack of break in each case of switch , since this construct can all be executed, understand it as um goto 'and not a decision mechanism, it pula for the first one that is valid, then just do not continue executing the others if you explicitly have it broken. I used to improve the code a bit:

#include <iostream>
using namespace std;

int main() {
    int item, qtde;
    float valor;
    cin >> item >> qtde;
    switch (item) {
    case 1:
        valor = 4.00;
        break;
    case 2:
        valor = 4.50;
        break;
    case 3:
        valor = 5.00;
        break;
    case 4:
        valor = 2.00;
        break;
    case 5:
        valor = 1.50;
        break;
    }
    cout << "Total: R$" << valor * qtde;
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

You have a better way to do this:

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

int main() {
    int item, qtde;
    cin >> item >> qtde;
    array<float, 5> valores = { 4.00, 4.50, 5.00, 2.00, 1.50 };
    cout << "Total: R$" << valores[item - 1] * qtde;
}

See running on ideone . And no Coding Ground . Also I placed GitHub for future reference .

    
16.08.2018 / 19:35