c++ - 从上次检查过去的 C++ 天数
问题描述
我想创建一个程序来跟踪用户上次给植物浇水的时间(手动检查)。所以基本上......用户按下一个按钮,程序将今天的日期设置为 date1,然后每天更新 date2。如果差值大于某个日期,则程序返回一个字符串。
int main() {
int time_elapsed = ; \\???
std::cout << needs_water(difference) << "\n";
}
这里是main函数,调用函数如下:
std::string needs_water(int days) {
if (days > 3){
return("Time to water the plant.");
}
else {
return("Don't water the plant!");
}
}
对不起我的英语不好,提前谢谢。
编辑:简而言之,我想知道的是如何告诉程序从上次检查过去了多少时间。
解决方案
这是一个应该做我理解你想要实现的例子。替换milliseconds
为days
(c++20) 或替换为hours
#include <iostream>
#include <string>
#include <chrono>
#include <thread>
using namespace std::chrono;
using namespace std::chrono_literals;
template<typename DurationT>
bool time_elapsed(DurationT time) {
static auto last_check = steady_clock::now();
auto now = steady_clock::now();
auto time_passed = now - last_check;
if (time_passed > time){
last_check = now;
return true;
}
else {
return false;
}
}
int main()
{
for(int i=0; i < 12; ++i) {
std::cout << (time_elapsed(milliseconds{3}) ?
"Time to water the plant!" :
"Don't water the plant!") << std::endl;
std::this_thread::sleep_for(1ms);
}
return 0;
}
推荐阅读
- celery - 将一个可迭代的任务结果链接到一个组,然后将该组的结果链接到一个和弦
- python - 如何添加自定义路径以保存 zip_file
- python - 如何在python中的另一个列表之间插入一个列表
- java - 当我想要更多并且如果语句不正确时,小数位不会超过 1
- java - 将 GIF 切割成帧并将其转换为像素的程序占用了太多内存
- css - 如何自定义音频标签中的暂停按钮?
- python - 将数据框中的所有列合并到列表中
- python - Python 单元测试:如何正确地对内部具有多个 func 调用的函数进行单元测试
- java - 如何退出返回类型为 int[] 的函数?
- powershell - Powershell - 单元格将 Excel 列格式化为小数位