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日

悬赏问题

  • ¥20 wireshark抓不到vlan
  • ¥20 关于#stm32#的问题:需要指导自动酸碱滴定仪的原理图程序代码及仿真
  • ¥20 设计一款异域新娘的视频相亲软件需要哪些技术支持
  • ¥15 stata安慰剂检验作图但是真实值不出现在图上
  • ¥15 c程序不知道为什么得不到结果
  • ¥40 复杂的限制性的商函数处理
  • ¥15 程序不包含适用于入口点的静态Main方法
  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来