Enclave_ 2022-06-29 19:11 采纳率: 88.5%
浏览 87
已结题

C++ 小程序 主进程和计时器如何同时运行

制作了一个猜数字的小程序,我想要用循环和sleep(1000)增加一个倒计时的功能 这个功能是输入一个单位位秒的时间 然后进行倒计时,倒计时结束后游戏自动停止
但是发现按游戏进程和倒计时进程无法同时进行
所以这个该怎么改
下面是我的写的小游戏进程代码

#include <iostream>
#include<cstdlib>
#include<ctime>
using namespace std;
int main()
{
    srand((unsigned int)time(NULL));
    int n=0;
    int num = rand() % 100 + 1; //生成1-100随机数
    cout << "please input a number (1-100):";
    while (n != num)
    {
        cin >> n;
        if (n > num)
        {
            cout << "too big" << endl;
        }
        else if(n<num)
        {
            cout << "to small" << endl;
        }
    }
    cout<<"the number is "<<num<<endl;
    system("pause");
    return 0;
}
  • 写回答

2条回答 默认 最新

  • a5156520 2022-06-29 19:35
    关注

    下面是没有使用线程来同步监控时间的办法(采用线程来监控时间,因为while循环因为要获取输入后才判断时间,所以时间误差度和不使用线程应该也差不多,但可能也有更好的实现,个人理解),仅在while循环前和获取输入和判断结果后简单统计使用时间来判断游戏时间是否没有超过指定时间,所以时间判断上稍有出入。
    参考链接:
    C++计时器(用于计算算法运行时间等)_KiraFenvy的博客-CSDN博客_c++计时器

    #include <iostream>
    #include<cstdlib>
    #include<ctime>
    using namespace std;
    int main()
    {
    //https://blog.csdn.net/m0_51371693/article/details/121589590
        srand((unsigned int)time(NULL));
        clock_t begin, end;
        double usetime ;
        
        int n=0;
        int num = rand() % 100 + 1; //生成1-100随机数
        cout << "please input a number (1-100):";
        begin = clock();
        while (n != num&&usetime<=10) //如果没有猜正数字以及游戏时间没有超过10秒 
        {
            
            cin >> n;
            if (n > num)
            {
                cout << "too big" << endl;
                
            }
            else if(n<num)
            {
                cout << "to small" << endl;
            }
            end = clock();
            usetime = double(end - begin) / CLOCKS_PER_SEC ;
            cout<<"game use "<<usetime<<" seconds, time left "<<10-usetime<<" seconds."<<endl;
        }
        cout<<"the number is "<<num<<endl;
        system("pause");
        return 0;
    }
    
    

    img

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论 编辑记录
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 7月10日
  • 已采纳回答 7月2日
  • 创建了问题 6月29日

悬赏问题

  • ¥15 Attention is all you need 的代码运行
  • ¥15 一个服务器已经有一个系统了如果用usb再装一个系统,原来的系统会被覆盖掉吗
  • ¥15 使用esm_msa1_t12_100M_UR50S蛋白质语言模型进行零样本预测时,终端显示出了sequence handled的进度条,但是并不出结果就自动终止回到命令提示行了是怎么回事:
  • ¥15 前置放大电路与功率放大电路相连放大倍数出现问题
  • ¥30 关于<main>标签页面跳转的问题
  • ¥80 部署运行web自动化项目
  • ¥15 腾讯云如何建立同一个项目中物模型之间的联系
  • ¥30 VMware 云桌面水印如何添加
  • ¥15 用ns3仿真出5G核心网网元
  • ¥15 matlab答疑 关于海上风电的爬坡事件检测