簡體   English   中英

為什么我的 If 和 Else 語句不執行任何操作? (c++)

[英]Why aren't my If and Else statements doing nothing? (c++)

我剛開始學習 c++,我正在嘗試制作一個骰子游戲,用戶輸入 1 到 6 之間的數字,然后代碼在該范圍內打印一個隨機數,如果 y 和 z 相同,你就贏了。

這是我擁有的代碼,但是當我輸入一個不在數組中的數字時,它就像在數組中一樣工作。


#include <iostream>
#include <stdlib.h>
#include <time.h>

int main() {
    for (; ; ) {
        int x[6] = { 1,2,3,4,5,6 }; //dice numbers
        int y;                      //user choice
        int z;                      // random number generated

        std::cout << "Pick a number between 1 and 6\n";
        std::cin >> y;

        if (y >= 1 || y <= 6) {     //if y is greater then or = to 1 or less then 
            std::cout << "Rolling dice, if your number is the correct number you win\n";
            srand(time(NULL));      //this makes rand() actually random.
            z = rand() % 6;
            std::cout << "The number is " << x[z] << "\n" << "The game will repeat..\n";
        }

        else {                      //if the num generated isn't within 1 or 6 this is printed
            std::cout << "ERROR: Generated number is not within 1 nor 6, try again.";

        }

        if (y == z) {
            std::cout << "Congratulations you rolled the right number";
        }
    }

(輸入是y) (數組是x) (你需要贏的數字是z)

我也可以更改它,以便它只讀取數組,以便用戶甚至可以輸入骰子的數量,如果這一切順利的話。

這個條件:

if (y >= 1 || y <= 6)

對於y的所有值都將成立。 每個 integer要么大於或等於 1,要么小於或等於 6。

你需要一個連詞,像這樣:

if (y >= 1 && y <= 6)

你也需要break; y == z時,否則你會得到一個無限循環。

我發現你的代碼有五個問題。

首先,你最好做while(true)而不是for(; ; )

其次,您的 else 塊應該從終止 if 塊的同一行開始。

第三,你應該在贏得比賽時插入一個break語句。

第四,您應該將條件if (y >= 1 || y <= 6)更改為if(y >= 1 && y <= 6) 兩者的區別在於|| 是 OR 邏輯運算符。 如果 y 大於或等於 1,或者如果 y 小於或等於 6,則這是正確的,這基本上適用於每個 integer。 999 會通過,因為它大於或等於 1,-999 會通過,因為它小於或等於 6。而且 1 和 6 之間的任何數字都會通過,因為它們會通過 y >= 1 和 y <= 6 . 如果你要插入一個 AND 運算符&&來代替 OR 運算符,那么條件就會通過,因為它只有在 y 介於 1 和 6 之間時才成立。

第五,您應該將條件為y == z的 if 塊移動到嵌套在y >= 1 && y <= 6中。 下面的代碼是我所做的每一個更改:

    while (true) { //1
        int x[6] = { 1,2,3,4,5,6 };
        int y;
        int z;

        std::cout << "Pick a number between 1 and 6\n";
        std::cin >> y;

        if (y >= 1 && y <= 6) { //4
            std::cout << "Rolling dice, if your number is the correct number you win\n";
            srand(time(NULL));
            z = rand() % 6;
            std::cout << "The number is " << x[z] << "\n" << "The game will repeat..\n";
            if (y == z) { //5
                std::cout << "Congratulations you rolled the right number";
                break; //3
            }
        } else { //2
            std::cout << "ERROR: Generated number is not within 1 nor 6, try again.";

        }
    }

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM