You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++编写石头剪刀布练习RNG 偶现结果错误是否与switch用法有关

这个问题和你使用switch语句没有任何关系,出现结算错误是两个编码错误导致的:

错误1:随机数种子初始化位置错误

rand()函数的随机数种子只需要在程序启动时设置1次即可,你把srand((unsigned)time(0))放在了do-while循环内部,每轮游戏都会重新设置种子。而time(0)返回的是秒级时间戳,如果你两轮游戏的操作间隔不到1秒,两次设置的种子完全相同,会导致多轮游戏生成的rng值完全重复,出现不符合预期的结果。

修正方案:把srand((unsigned)time(0))移动到main函数最开头,do-while循环外部。

错误2:胜负判断硬编码逻辑错误

你代码中rng的取值对应电脑出拳的规则是:rng=1=石头、rng=2=布、rng=3=剪刀,但你在每个rng对应的case分支内,错误地根据用户输入修改了电脑出拳的输出和胜负判定。
举个例子:rng=1分支本应固定判定电脑出石头,但你在该分支下用户输入布p时,错误输出「电脑使用了布」并判定用户输,而正确逻辑应该是用户出布赢石头,判定用户获胜。你所有rng分支下都存在类似的逻辑错位问题。


修正后参考代码

#include <cstdlib>
#include <ctime>
#include <iostream>

using namespace std;

int main() {
    char answer;
    int rng;
    int cont = 0;
    // 随机数种子全局仅初始化一次
    srand((unsigned)time(0));

    do {
        rng = (rand() % 3) + 1;
        cout << "r for rock, p for paper, s for scissors \n";
        cout << "please enter your hand: ";
        cin >> answer;

        // 固定输出电脑出拳,避免重复编码出错
        switch (rng) {
            case 1: cout << "The computer used rock! \n"; break;
            case 2: cout << "The computer used paper! \n"; break;
            case 3: cout << "The computer used scissors! \n"; break;
        }

        // 统一做胜负判断
        if ((rng == 1 && answer == 'r') || (rng == 2 && answer == 'p') || (rng == 3 && answer == 's')) {
            cout << "It's a draw.\n";
        } else if ((rng == 1 && answer == 'p') || (rng == 2 && answer == 's') || (rng == 3 && answer == 'r')) {
            cout << "You win! \n";
        } else {
            cout << "You lose. \n";
        }

        cout << "enter 1 to continue: ";
        cin >> cont;
    } while (cont == 1);
    return 0;
}

内容的提问来源于stack exchange,提问作者ChinoP

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 23:15:03