gpt4 book ai didi

C++ - 如何制作一个简单的计时器,我将如何使用基于它的 if 语句?

转载 作者:行者123 更新时间:2023-11-28 01:42:53 25 4
gpt4 key购买 nike

我正在制作一种虚拟宠物。在某种程度上,我在复制电子鸡。

// VirtualPetProjClassesandObjectsPRCT.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <iostream>
#include <string>
#include <cmath>
#include "Vpet.h"

int main()
{
// Set Name & General Info
std::string pop;
std::cout << "What would you like to call your pet?" << std::endl;
std::cin >> pop;
std::cout << "List of commands you can do with " << pop << std::endl << "'state'" << std::endl << "'quit'" << std::endl << "'feed'." << std::endl;
std::cout << "If you feed bob less than quarter his weight he will gain weight but still be hungry!" << std::endl;
std::cout << "Bob weighs 50 kgs!" << std::endl;

VPet bob(50, false);
bob.feedPet(5);
do
{
//input
std::string input;
std::cin >> input;

if (input == "Quit" || input == "quit")
{
return 0;
}

if (input == "Feed" || input == "feed")
{
std::cout << "Enter the amount you would like to feed " << pop << " - ";
int x;
std::cin >> x;
if (x > (bob.getWeight() * 0.5))
{
std::cout << "Bob can't eat that much!" << std::endl;
}
else
{
bob.feedPet(x);
std::cout << "You have fed " << pop << " " << x << " kgs of food!" << std::endl;
}
}

// State
if (input == "State" || input == "state")
{
std::cout << pop << " weighs: " << bob.getWeight() << std::endl;

if (bob.getHungry())
{
std::cout << pop << " is hungry." << std::endl;
}
else
{
std::cout << pop << " is not hungry." << std::endl;
}
}
} while (0 != 1);
}

我创建了一个类和一些函数来喂养宠物,检查它的重量以及他是否饿了,但我还想制作一个时钟,每隔几分钟或几秒钟就会检查一下时间过去了多少,是否一定数量过去了,我会使用我之前定义的 bool 变量打印出虚拟宠物饿了。谢谢。

最佳答案

您可以使用库 chrono 来测量时间跨度,然后采取相应的行动。

#include <chrono>
#include <ctime>
#include <iostream>
#include <thread>

int main () {
auto start = std::chrono::system_clock::now();

while (1) {
std::this_thread::sleep_for(std::chrono::milliseconds(100));

// In your real code you will perhaps not need the sleep

const auto now = std::chrono::system_clock::now();
const auto duration = now - start;
if ( duration.count() > 2e9) {
break;
}

std::cout << "waiting ..." << std::endl;
}

std::cout <<"done" << std::endl;
}

time ./chrono_example 这个输出:

等待...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...等待 ...完成

真正的 0m2.013s

用户 0m0.002s

系统 0m0.004s

关于C++ - 如何制作一个简单的计时器,我将如何使用基于它的 if 语句?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46465579/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com