python-猜数字游戏
具体规则以及代码的c++版本就参见文章:https://blog.csdn.net/weixin_44991673/article/details/100811733
python代码如下:
import random
num = random.randint(1,100) # 生成1到100之间的一个随机整数 1<= a <=100
print(num) # 在真实游戏时这句话要注释掉哦!!
while(1):
guess_num = int(input('Please enter the number you guesse (integer between 1 and'
' 100, end of carriage return):')) # input输入为字符串。因此要先转换为整数
if guess_num >=1 and guess_num<=100:
break
else:
print('please enter a number between 1 and 100!!')
while(1):
if guess_num == num:
print('Congratulations, you have guessed the right number:',num)
break
if guess_num<num:
print('The guess is less than the true value!')
guess_num = int(input('Please enter the number you guesse (integer between 1 and'
' 100, end of carriage return):'))
if guess_num>num:
print('The guess is greater than the true value!')
guess_num = int(input('Please enter the number you guesse (integer between 1 and'
' 100, end of carriage return):'))
结果如下:
涉及知识:
随机数的产生:num = random.randint(1,100) # 生成1到100之间的一个随机整数 1<= a <=100。
更详尽的随机数产生参见:https://www.cnblogs.com/yunlongaimeng/p/8639963.html
num = input():num为字符串形式。
break的作用:跳出并且结束循环(注意continue是仅仅跳出本次循环,并不会终止循环)。
c+±猜数字游戏
c++代码:
#include <iostream>
#include <ctime>
#define random(a,b) (rand()%(b-a)+a) //generate a integer between a and b
using namespace std;
int main()
{
int num = 0;
int guess_num = 0;
srand((int)time(0)); // 产生随机种子 把0换成NULL也行
num = random(1,100);
cout << num << endl; //真正游戏时也要去掉哦!
while(1)
{
cout << "Please enter the number you guess (integer between 1 and 100, end of carriage return):" << endl;
cin >> guess_num;
//cout << int(guess_num) << endl;
if(guess_num<=100 and guess_num>=1)
{
cout <<"right number"<< endl;
break;
}
else{
cout << "Please enter the number you guess (integer between 1 and 100, end of carriage return):" << endl;
cin >> guess_num;
}
}
while(guess_num != num){
if(guess_num<num){
cout<<"The guess is less than the true value!"<<endl;
cout << "Please enter the number you guess :" << endl;
cin >> guess_num;
}
if(guess_num>num){
cout<<"The guess is greater than the true value!"<<endl;
cout << "Please enter the number you guess :" << endl;
cin >> guess_num;
}
}
cout<<"Congratulations, you have guessed the right number:"<<num<<endl;
/*return 0;*/
}
运行结果:
涉及知识:(参见文章[https://www.cnblogs.com/xiaokang01/p/9786751.html#_label0_2])
随机数的产生,伪随机数和随机种子的概念。rand()和srand()的用法
c++中的宏定义