C++ 学习循环结构小案例
#include<iostream> using namespace std; #include<ctime> //随机猜数字1~100 int main() { //添加随机数种子:利用当前系统时间生成随机数,防止每次随机数都一样 srand((unsigned int)time(NULL)); int num = rand() % 100 + 1; int val = 0; int i = 0; int b = 5; cout << "猜数字游戏\t" << endl; cout << "请输入一个1~100的数字" << endl; while (1) { cin >> val; if (val > num) { cout << "您猜大了" << endl; i++; } else if (val < num) { cout << "您猜小了" << endl; i++; } else { cout << "恭喜您猜对了" << endl; break; } if(i>=b) //如果猜错次数超过设定数字,则挑战失败,游戏结束 { cout << "您已猜错 "<<b<<" 次,挑战失败" << endl; break; } cout << "您还剩 " << (b - i) << " 次机会" << endl; } system("pause"); return 0; }
TRANSLATE with x English TRANSLATE with COPY THE URL BELOW Back EMBED THE SNIPPET BELOW IN YOUR SITE Enable collaborative features and customize widget: Bing Webmaster Portal Back