簡體   English   中英

C ++:如何使代碼自動輸入隨機數?

[英]C++: How can I make the code auto input random numbers?

我正在研究這個簡單的代碼,總之,它應該一直要求您輸入的數字與您嘗試輸入的次數不同,因此,它將開始要求您不要輸入0,只要您輸入不要輸入0,它會重申並要求您不要輸入1。

但是,我想修改該程序,以使其能夠嘗試隨機輸入來運行,只是想知道在獲得正確的數字之前它將運行多長時間。

在卡住之前,這是我想到的:

#include <iostream>

//i was told the following libraries give you random numbers
#include <time.h>
#include <cstdlib> 
#include <conio.h>

using namespace std;

int main() {
    int numberAttempts = -2;
    int numberEntered = !(numberAttempts);

    int xRan;    // I was told this little bit should get you random numbers
    srand(time(0));

    xRan = rand() % 100 + 1; //arbitrary randomization rule

    while (!((numberAttempts+1)==numberEntered)){

        int counter = numberAttempts + 2;

        cout << "Please enter any number but " << counter
             << ".\n>>";

        numberEntered ==  //here is where i'd like to have a random input. 

        cout << "Number Entered: " << numberEntered
             << endl;
        numberAttempts++;

        }
    cout << "\n\nWhy the did you do that?\n\n\n\n";

    system("pause");
    return 0;
}

設置號numberEntered = xRan; 使它與在第一次迭代中將numberEntered設置為0相同:它會響應但立即關閉。

我堅信這只是重新分配numberEntered的問題,但我不知道如何。

預先感謝您的關注。

這很簡單,將while()循環中的rand() % 100 + 1xRan移到numberEntered 實際上,您可以完全xRan變量。 您的代碼已實現,如下所示。 但是請注意,因為如果嘗試次數超過100而未與numberAttempts匹配,則隨機函數將僅返回1-100之間的值,因此循環將永遠運行並最終崩潰。 為了解決這個問題,我在while循環中放入了另一個必要條件!((numberAttempts+1)==numberEntered) && (numberAttempts < 100)

#include <iostream>

//i was told the following libraries give you random numbers
#include <time.h>
#include <cstdlib> 
#include <conio.h>

using namespace std;

int main() {
    int numberAttempts = -2;
    int numberEntered = !(numberAttempts);

    srand(time(0));

    while (!((numberAttempts+1)==numberEntered) && (numberAttempts < 100)){

        int counter = numberAttempts + 2;

        cout << "Please enter any number but " << counter
             << ".\n>>";

        numberEntered = rand() % 100 + 1;

        cout << "Number Entered: " << numberEntered
             << endl;
        numberAttempts++;

        }
    cout << "\n\nWhy the did you do that?\n\n\n\n";

    system("pause");
    return 0;
}

注意:此代碼並非每次都有效。 以下是工作迭代 工作迭代

暫無
暫無

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

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