问题描述
#include <iostream>
#include <ctime>
using namespace std;
int main()
{
double seconds;
struct tm birth = {0}; //10-28-1955
birth.tm_year = 55;
birth.tm_mon = 9;
birth.tm_mday = 28;
birth.tm_sec = 0;
struct tm present = {0}; //2-10-2021
present.tm_year = 121;
present.tm_mon = 1;
present.tm_mday = 10;
present.tm_sec = 0;
time_t p1 = mktime(&present);
time_t b1 = mktime(&birth);
seconds = (difftime(p1,b1));
seconds /= 86400;
cout << "Bill "
<< "Gates- " << seconds << "days" << endl;
}
输出:
Bill Gates- 18668.2days
我正在尝试使用 <ctime>
来计算比尔·盖茨在 2-10-2021 之前还活着的天数。我得到了 18668.2 的答案;这还差得很远,因为它实际上应该是大约 20000 天。
调试时,一切正常,直到第 21 行。
当它到达第 22 行时,b1
变为 -1。
我不知道如何解决这个问题。我为 struct birth
设置的日期看起来不错。
解决方法
当它到达第 22 行时,b1 变为 -1。
抱歉,您的 C 标准库不足以处理您的日期。使用(或编写)一个不同的库来表示 1970 年之前的时间。
在此期间,您使用的是 C++ - 无需使用 C 函数。尝试使用 chrono library,它是 C++ 标准库的一部分。