我如何在c++上的数字游戏中添加一个以秒为单位的计时器



我试着做了一个猜数字游戏,我想添加一个计时器,这样用户就可以看到他猜了多少秒。有人能帮我添加一个以秒为单位的计时器吗?这是代码(不要介意#include,我不知道我需要哪一个xD(:

#include <bits/stdc++.h>
#include <unistd.h>
#include <stdlib.h>
#include <iomanip>
using namespace std;
int main()
{
int randomnr, guesses=0, yournr, timer=0;

srand (time(NULL));
randomnr = rand () % 100;

cout << randomnr << "n";

while (yournr != randomnr)
{
cin >> yournr;

if (yournr == randomnr && guesses == 0) 
{
cout << "Wow you guessed it from the start!";
break;
}

if (yournr < randomnr)
{
cout << "Your number is lower than the random one! Try again!" << "n";
guesses++;
}
else
if (yournr > randomnr)
{
cout << "Your number is bigger than the random one! Try again!" << "n";
guesses++;
}
else
if (yournr == randomnr) 
{
cout << "You guessed with " << guesses << " guesses and " << timer << " seconds, well done!" << "n";
}
}
return 0;
}

使用chrono库对代码进行了一些小的更改:

// these two headers should do ;)
#include <iostream>
#include <chrono>
using namespace std;
using namespace chrono;
int main()
{
int randomnr, guesses=0, yournr;
system_clock::time_point start = system_clock::now();
srand (start.time_since_epoch().count());
// [...]
cout << "You guessed with " << guesses << " guesses and " << duration_cast<seconds>((system_clock::now() - start)).count() << " seconds, well done!" << "n";
// [...]
return 0;
}

duration_cast有助于将两个time_point之间的间隔强制转换为给定的duration类型(在本例中,强制转换为seconds(。对结果调用count()会返回实际数字(因为seconds是一个非平凡类型(。

相关内容

最新更新