C++代写:CS1160 Random Number Guessing Game

Introduction

Random Number只是一个数学的概念,在计算机领域,由于精度原因,并不存在严格的数学意义上的随机数,所有所谓的随机数实质上都是伪随机数
但是,结合外部系统,计算机也是能产生真随机数的。一个典型的例子就是UNIX内核中的随机数发生器,也就是(/dev/random)设备。
它是怎么做到的呢?
UNIX本质上维护了一个熵池,不停的采集外部设备的非确定性/随机事件,如I/O,中断等,并将这些事件作为随机数的种子来使用。
因此,虽然程序和算法本身不能产生真随机数,但是作为计算机整体,还是可以依赖外部熵来产生真随机数的。

Requirement

Write a program that generates a random number and asks the user to guess what the number is. If the user’s guess is higher than the random number, the program should display “Too high, try again.” If the user’s guess is lower than the random number, the program should display “Too low, try again.” The program should use a loop that repeats until the user correctly guesses the random number.
You should also keep a count of the number of guesses that the user makes. When the user correctly guesses the random number, the program should display the number of guesses.

Analysis

本题需要利用随机数来实现一个猜大小的游戏。随机数的产生可以利用stdlib.h中提供的rand()函数来实现。rand()函数本质上也是利用UNIX的随机数发生器得到算法种子,进行运算后得到相应的随机数。

Tips

下面给出部分关键代码的实现

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <stdlib.h>
#include <iostream>

using namespace std;

int main()
{

int guess_number;
int random_number = rand() % 50;
while (true) {
cout << endl << "Enter a number between 0 and 50: ";
cin >> guess_number;
if (guess_number == random_number) {
cout << "You got the correct number!" << endl;
break;
} else if (guess_number < random_number) {
cout << "Too low, try again.";
} else if (guess_number > random_number) {
cout << "Too high, try again.";
}
}
return 0;
}

执行结果

1
2
3
4
5
6
7
8
9
10
11
12
Enter a number between 0 and 50: 25
Too low, try again.
Enter a number between 0 and 50: 40
Too high, try again.
Enter a number between 0 and 50: 30
Too low, try again.
Enter a number between 0 and 50: 35
Too high, try again.
Enter a number between 0 and 50: 32
Too low, try again.
Enter a number between 0 and 50: 33
You got the correct number!