用c++语言函数模版做猜价格游戏,可以猜8次
时间: 2024-03-26 17:36:02 浏览: 13
好的,我来为您提供一个简单的猜价格游戏程序:
```cpp
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
template <typename T>
void guess_price(T answer, int max_try = 8){
int guess;
int tries = 0;
while (tries < max_try){
cout << "请输入您猜测的价格:" << endl;
cin >> guess;
tries++;
if (guess == answer){
cout << "恭喜您猜对了!" << endl;
return;
}
else if (guess < answer){
cout << "猜小了,请再试一次。" << endl;
}
else{
cout << "猜大了,请再试一次。" << endl;
}
}
cout << "很遗憾,您没有猜中。正确的价格是:" << answer << endl;
}
int main(){
srand(time(0)); // 初始化随机数种子
int answer = rand() % 101; // 生成0-100之间的随机数
guess_price(answer);
return 0;
}
```
以上代码定义了一个函数模板`guess_price`,用于猜价格游戏。其中,`answer`参数表示正确答案,`max_try`参数表示最多可猜测的次数,默认为8次。程序通过随机数生成一个0-100之间的价格,然后调用`guess_price`函数让用户进行猜测。如果猜对了,函数会输出恭喜信息并结束;如果猜错了,函数会根据猜测大小给出提示,直到达到最大猜测次数为止。如果用户没有猜中,函数会输出正确答案并结束。