Switch entering wrong case

Asked

Viewed 145 times

2

I’m trying to solve the Uri 1038 problem using switch, apparently the values are merging, Item 3 for example, multiplying by 2 (5 x 2) returns the value 3. What I’m 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;
}

Dados de entrada

  • 3

    I think the switch is running without pauses. Some were missing breaks in your code. See switch statement.

  • You’re squealing from the break's

  • @Andersoncarloswoss Caraca, I studied it yesterday and forgot about the break anyway. But even now with the right breaks in each condition continues to give the same result. Edit: I closed the VS and opened the project again and is now running ok, thanks!

1 answer

2


The problem with this code is the lack of break in each case of switch, since this construction can all be executed, understand it as um goto` and not a decision mechanism, it jumps to the first that is valid, then just doesn’t keep running the rest if you explicitly tell it to break. I took the opportunity to improve the code a little:

#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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

There’s 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;
}

Behold working in the ideone. And in the repl it.. Also put on the Github for future reference.

  • Thanks Maniero and Anderson Carlos, I really floated on break, studied yesterday and forgot about the poor guys on Switch. Still haven’t got much Array and didn’t risk doing, but seeing now your solution with it really is much better and simple, Fight!

Browser other questions tagged

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