C++:如何让代码自动输入随机数?

标签 c++

我正在编写这个简单的代码,总而言之,它应该不断要求您输入一个与您尝试输入的次数不同的数字,因此,它会开始要求您不要输入 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 的问题,但我不知道如何。

预先感谢您的关注。

最佳答案

移 Action 业很简单 rand() % 100 + 1来自 xRannumberEntered在 while 循环内。您实际上可以完全取消 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;
}

注意:此代码并非每次都有效。 下面是一个工作迭代 Working iteration

关于C++:如何让代码自动输入随机数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33719332/

相关文章:

c++ - nullptr 是否用于终止 C 风格的字符串?

c++ - 获取终端窗口的大小(行/列)

C++ 将排列结果插入 vector

c++ - 如何使用移位运算符 << 分配 BH1750 光传感器中的值?

c++ - C/C++ 中的 JSON <-> XML

c++ - 使用Kinect调用Open Gl的鼠标功能

C++ 模板<运算符>

c++ - 检查空字符 C++

c++ - SDL 增量时间重置

c++ - 隐式转换以适应现有构造函数