2014-12-03 37 views
1

你好我正試圖通過使用用戶輸入的日子來計算一個人的生日。我對ctime圖書館很陌生,但是我想到的是獲得天數的兩個日期之間的差異。從我的知識中,我確實有ctime;我知道ctime有一個由min,secs,hour,day,month和year組成的struct tm。我嘗試使用asctime將它們放入個體中,但它使我的邏輯更加混亂。我使用difftime來查找日期之間的差異。像這樣:根據用戶輸入的天數計算生日

struct tm a = { 0, 0, 0, 1, 1, 91 }; /* my birthday */ 
struct tm b = { 0, 0, 0, 3, 11, 114 }; /* today's date */ 
time_t x = mktime(&a); 
time_t y = mktime(&b); 
if (x != (time_t)(-1) && y != (time_t)(-1)) 
{ 
    double days = difftime(y, x)/(60 * 60 * 24); 
    cout << ctime(&x); 
    cout << ctime(&y); 
    cout << "difference = " << days << " days" << endl; 
} 

輸出爲:differnce =8706天

的問題是,用戶輸入8706天讓我的生日或生日。如果有意義,這個代碼反向。你能幫我弄清解決問題的邏輯嗎?

回答

0

我沒有得到你真正想要的東西,但是如果你想讓用戶輸入天數,你會得到他的生日很容易,只需寫 struct tm a = {0,0,0,a, b,c};/*我的生日*/ ,如果天數爲8706 int c = 8706/365; //最大的除數,它應該給你23 ,你會得到其餘的 int temp = 23 * 365 = 8395; 然後您將使 int剩餘= 8706-8395 = 311; 和你繼續找到月份和日期.. 希望這是你的問題。

+0

它幫助一點,也許我沒有問更詳細,但即時尋找;假設用戶輸入自出生以來的天數,則應該從今天的日期輸出用戶生日 – 2014-12-03 16:18:19

+0

#include #include using namespace std; void main() { \t int天,日,月,年; \t cout <<「你幾歲在幾歲」<< endl; \t cin >> days; \t year = days/365; \t \t int remaining = days-(year * 365); \t \t month = remaining/30; \t \t其餘=剩餘 - (月* 30); \t \t day = remaining; \t struct tm a = {0,0,0,3天,11個月,114年};/*我的生日*/ \t struct tm b = {0,0,0,3,11,114};/*今天的日期*/ \t time_t的X = mktime(&a); \t time_t的Y = mktime(&b); \t \t COUT <<的ctime(&x); \t \t COUT <<的ctime(&y); \t \t }也許這個代碼將幫助和你可以使用a.tmday和b.tmyear等。 – yazan 2014-12-03 16:34:36

+0

非常感謝這正是我所需要的 – 2014-12-03 18:21:48

0

如果你可以使用Boost

#include <iostream> 
#include "boost/date_time/gregorian/gregorian.hpp" 

using namespace std; 
using namespace boost::gregorian; 

int main(){ 
    days d; 
    cin >> d; 
    date today = day_clock::local_day(); 
    date birth = today - d; 
    date bday(today.year(), birth.month(), birth.day()); 
    if(bday < today) bday = date(today.year()+1, birth.month(), birth.day()); 
    cout << bday; 
} 
+0

無法訪問boost庫我不斷收到一條錯誤消息,說它無法打開源碼 – 2014-12-03 18:25:24

+0

Boost不是一個部分標準庫的庫,你必須停下來加載並在編譯期間將其作爲包含路徑添加(如果使用gcc,則使用-I標誌(大寫「i」))。更多信息:http://www.boost.org/doc/libs/1_57_0/more/getting_started/index.html – 2014-12-03 18:48:35