我是靠谱客的博主 迅速鸭子,这篇文章主要介绍C++猜数字游戏的程序,用srand()函数产生随机数,现在分享给大家,希望可以做个参考。

/*
编写一个猜数字游戏的程序:程序随机选择一个1到1000的数,然后输出:
    I have a number between 1 and 1000.    
    Can you guess my number?
    Please type your first guess:
    接着,游戏者输入一个结果。程序根据比较结果输出以下三条信息之一:
    1)Excellent! You guessed the number!
         Would you like to play again (y or n)?
    2)Too low.Try again.
    3)Too high.Try again.
如果游戏者猜错,则程序进行循环,直到猜对。程序通过Too high或Too low消息帮助学生接近正确答案。请思考:怎样才能猜得最快?
*/

复制代码
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
<span style="font-size:14px;">#include<iostream> #include <cstdlib> #include<time.h> using namespace std; int RNG() //此函数用于产生随机数 { int Random_number; srand(time(0));<span style="white-space:pre"> </span>//获取系统时间来作为种子 Random_number=1+rand()%1000; return Random_number; } int main() { int Random_number,guss_number; char yes_no; while(true) { Random_number=RNG(); cout<<Random_number<<endl;//输出系统产生的随机数,免得难得猜。 cout<<"I have a number between 1 and 1000"<<endl; cout<<"Can you guess my number?"<<endl; cout<<"Please type your first guess:"; cin>>guss_number; while(guss_number<1||guss_number>1000) { cout<<"Input error,once again!"; cin>>guss_number; } while(true) { if(guss_number==Random_number) { cout<<"Excellent! You guessed the number!"<<endl; cout<<"Would you like to play again (y or n)?:" ; cin>>yes_no; if(yes_no=='n') { exit(0); //返回操作系统 } else { break; //跳出第一层循环 } } if(guss_number<Random_number) { cout<<"Too low.Try again "; cin>>guss_number; while(guss_number<1||guss_number>1000) { cout<<"Input error,once again!"; cin>>guss_number; } } if(guss_number>Random_number) { cout<<"Too high.Try again "; cin>>guss_number; while(guss_number<1||guss_number>1000) { cout<<"Input error,once again!"; cin>>guss_number; } } } } return 0; } </span>

运行截图如下:


最后

以上就是迅速鸭子最近收集整理的关于C++猜数字游戏的程序,用srand()函数产生随机数的全部内容,更多相关C++猜数字游戏内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(73)

评论列表共有 0 条评论

立即
投稿
返回
顶部