用c ++写跳楼梯代码
时间: 2024-02-19 17:58:25 浏览: 14
以下是一个简单的 C++ 代码示例,用于模拟跳楼梯游戏:
```
#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
// 初始化楼层数和当前位置
int stairs = 10;
int position = 0;
// 设置随机数种子
srand(time(0));
// 开始跳楼梯游戏
while (position < stairs) {
// 随机生成跳的步数
int steps = rand() % 3 + 1;
// 更新当前位置
position += steps;
// 打印跳的步数和当前位置
cout << "跳了 " << steps << " 步,当前位置是 " << position << endl;
}
// 判断游戏结果
if (position == stairs) {
cout << "恭喜你跳完了楼梯!" << endl;
} else {
cout << "很遗憾,跳楼梯失败了。" << endl;
}
return 0;
}
```
这段代码使用了 C++ 标准库中的 rand 函数来随机生成跳的步数,然后通过 while 循环不断更新当前位置,直到跳完所有楼层。最后判断游戏结果并输出相应的提示信息。注意,为了确保每次随机数的不同,我们使用了 time 函数来设置随机数的种子。