In a switch case statement, it says “duplicate case value” comes up as an error. Anyone know why?

后端 未结 5 718
余生分开走
余生分开走 2021-01-12 12:13

I am working on a rock paper scissors program, but this time the computer chooses rock half the time, scissors a third of the time, and paper only one sixth of the time. The

5条回答
  •  执念已碎
    2021-01-12 12:25

    That switch statement does not do what you think.

    Each case defines one value that the value of computer is matched against. Combining several values with logical disjunction to give the value associated with a single case label does not make the corresponding block be entered when the value of computer is equal to any of those values, but rather when it is equal to the result of their logical OR combination. Not very meaningful, indeed.

    This is how you could rewrite your switch statement in order to make more sense:

    switch(computer) {
        case rock1: // Is it rock1?
        case rock2: // Or perhaps rock2?
        case rock3: // Or maybe rock3?
            c = 1;  // Well, if it's one of the above, do this...
            break;
        case scissors1: // OK, it wasn't. So is it scissors1?
        case scissors2: // Or scissors2?
            c = 3;      // If it's one of the above, do this...
            break;
        case paper: // So is it paper?
            c = 2;
            break;
        default: // Always better to be explicit about this
            break;
    }
    

提交回复
热议问题