demo1:一个猜数游戏

2019-08-17  本文已影响0人  Bug2Coder
#include<iostream>
#include<cstdlib>
#include<ctime>
#include<conio.h>
#include<Windows.h>
#include<string.h>    // 字符串变量引用时,需要导入此头文件

#define random(a,b) (rand()%(b-a)+a)
using namespace std;
//猜数游戏,三次机会

// 获取用户名函数
std::string getUsername() {
    const int MAX_LEN = 100;
    char szBuffer[MAX_LEN];
    DWORD len = MAX_LEN;
    if (GetUserName(szBuffer, &len))     //用户名保存在szBuffer中,len是用户名的长度
        return szBuffer;
    else
        return "";
}

int main() {
    std::string ss = getUsername();
    cout << ss << "欢迎您体验猜数游戏!!!" << endl;
    while (true) {
        string cc = "您将有三次机会...";    // 创建字符串变量
        cout << cc << endl;
        int num = 0;
        int count = 3;
        srand((int)time(0));  // 用时间戳产生随机种子
        num = random(1, 10);
        int a = 0;
        for (int i = 0; i < 3; i = i + 1) {
            cout << "请输入一个数字(范围1-10):";
            cin >> a;
            cout << "您输入的数字是:" << a << endl;
            if ( a > num) {
                cout << "数字大了" << "还有次数:" << 2 - i << endl;
            }
            else if (a < num) {
                cout << "数字小了" << "还有次数:" << 2 - i << endl;
            }
            else {
                cout << "恭喜您,猜对了!!!" << endl;
                break;
            }
        }
        cout << "游戏结束,您还接着玩游戏吗?退出请关闭本程序!!!" ;
        system("pause");
        cout << "---------------------------------------------------------------------" << endl;
    }
    
    return 0;

}
上一篇 下一篇

猜你喜欢

热点阅读