为什么我的srand会返回所有结果?

Tyl*_*con -7 c++ random srand

这是一个简单的文字游戏的开始.在游戏中,你应该四处寻找地下城并收集文物.我习惯srand(time(0))做一些事情,比如找到要进入的阶段,攻击,以及你找到的项目,我已经在编程中走得很远,但我已经遇到了问题.我的rand()返回所有结果.当我运行游戏时(这不是完整的代码,顺便说一句),它会返回"你进入了一个地牢!","哦不,敌人已经到了!",并且"你找到了一件神器!

void mainScreen()
{
    srand(time(0));
    cout << "Health: \n";
    cout << health;
    cout << endl;
    _sleep(500);
    cout << "Inventory: \n";
    cout << inventory;
    cout << endl;
    _sleep(500);
    cout << "Gold: \n";
    cout << gold;
    cout << endl;
    _sleep(500);
    cout << "Artifacts: \n";
    cout << artifacts;
    cout << endl;
    _sleep(500);
    cout << "Rolling the dice of fate... \n";
    int diceRoll = 1 + (rand() % 10);
    if (diceRoll = 1, 2, 3, 4, 5, 6) {
        cout << "You entered a dungeon! \n";
    }
    if (diceRoll = 7, 8) {
        cout << "Oh No! An enemy has arrived! \n";
    }
    if (diceRoll = 9, 10) {
        cout << "You found an artifact! \n";
    }
}
Run Code Online (Sandbox Code Playgroud)

Rem*_*eau 5

你的if陈述不符合你的想法.

首先,=当您应该使用==比较运算符时,您正在使用赋值运算符.

其次,您正在使用,运算符,该运算符计算左右表达式,然后返回正确表达式的结果.

所以,这段代码:

if (diceRoll = 1, 2, 3, 4, 5, 6)
{
    ...
}
if (diceRoll = 7, 8)
{
    ...
}
if (diceRoll = 9, 10)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

有效地做到这一点,这不是你想要的:

diceRoll = 1;
if (6)
{
    ...
}
diceRoll = 7;
if (8)
{
    ...
}
diceRoll = 9;
if (10)
{
    ...
}
Run Code Online (Sandbox Code Playgroud)

你需要这样做:

if ((diceRoll == 1) ||
    (diceRoll == 2) ||
    (diceRoll == 3) ||
    (diceRoll == 4) ||
    (diceRoll == 5) ||
    (diceRoll == 6))
{
    cout << "You entered a dungeon! \n";
}
else if ((diceRoll == 7) ||
        (diceRoll == 8))
{
    cout << "Oh No! An enemy has arrived! \n";
}
else
{
    cout << "You found an artifact! \n";
}
Run Code Online (Sandbox Code Playgroud)

可以使用范围比较简化:

if ((diceRoll >= 1) && (diceRoll <= 6))
{
    cout << "You entered a dungeon! \n";
}
else if ((diceRoll >= 7) && (diceRoll <= 8))
{
    cout << "Oh No! An enemy has arrived! \n";
}
else
{
    cout << "You found an artifact! \n";
}
Run Code Online (Sandbox Code Playgroud)

或者用一个switch声明代替:

switch (diceRoll)
{
    case 1:
    case 2:
    case 3:
    case 4:
    case 5:
    case 6:
    {
        cout << "You entered a dungeon! \n";
        break;
    }

    case 7:
    case 8:
    {
        cout << "Oh No! An enemy has arrived! \n";
        break;
    }

    case 9:
    case 10:
    {
        cout << "You found an artifact! \n";
        break;
    }
}
Run Code Online (Sandbox Code Playgroud)

另外,在旁注中,你不应该srand()每次mainScreen()都调用(我假设在程序的生命周期内可以多次调用). srand()应该只调用一次,所以你应该main()在调用之前调用它mainScreen().