用C++写一个新年倒计时代码
时间: 2024-06-14 22:05:28 浏览: 117
C++元旦倒计时代码祝福
以下是用C++写的一个新年倒计时代码的例子:
```cpp
#include <iostream>
#include <ctime>
int main() {
// 获取当前时间
time_t now = time(0);
// 将当前时间转换为tm结构体
tm *ltm = localtime(&now);
// 设置新年的日期
tm newYear;
newYear.tm_sec = 0;
newYear.tm_min = 0;
newYear.tm_hour = 0;
newYear.tm_mday = 1;
newYear.tm_mon = 0; // 一月
newYear.tm_year = ltm->tm_year + 1900; // 当前年份
// 计算距离新年的秒数
time_t newYearTime = mktime(&newYear);
int secondsLeft = difftime(newYearTime, now);
// 计算天、时、分、秒
int days = secondsLeft / (24 * 60 * 60);
int hours = (secondsLeft % (24 * 60 * 60)) / (60 * 60);
int minutes = (secondsLeft % (60 * 60)) / 60;
int seconds = secondsLeft % 60;
// 输出倒计时结果
std::cout << "距离新年还有:" << days << "天 " << hours << "小时 " << minutes << "分钟 " << seconds << "秒" << std::endl;
return 0;
}
```
阅读全文