2013-10-13 39 views
0

我有一个8位数int存储日期。例如12041989是1989年4月12日。我应该声明什么类型的变量日期以及如何提取年份?从8位整数提取年份(ddmmyyyy)

编辑:随着你告诉我,我这样做是这样的:(我有输入查询当前的日期和出生日期来计算一个人的年龄)

#include <stdio.h> 
#include <conio.h> 
void main() 
{ 
    unsigned int a, b, ac, an, c; 
    printf("\n Current date zzllaaaa \n"); 
    scanf("%d", &a); 
    printf("\n Date of birth zzllaaaa \n"); 
    scanf("%d", &b); 
    ac = a % 10000; 
    an = b % 10000; 
    c = ac - an; 
    printf("\n Age is: %d", c); 
    getch(); 
} 

有时它的工作原理,但有时它不,我不明白为什么。例如对于1310201312061995它告诉我,年龄是-3022。这是为什么?

+2

如果您尝试任何操作,请发布您的代码。 – Gangadhar

+0

这个问题不应该关闭。虽然OP没有发布代码,但是他没有要求代码**。他只是查询变量来存储日期以及如何从该变量中提取数字(年份)。我投票重新开放。 – haccks

+2

Puh租赁。这对你来说可能是显而易见的,它可能在你的介绍编程教科书的第一章(虽然可能不是),但这并不意味着提问者可以很容易地得到答案。显示一些基本的礼貌。 – Potatoswatter

回答

3

如果你不关心有5个或更多的数字表示年份日期,你可以使用模运算符:

int date = 12041989; 
int year = date % 10000; 

类型int通常为32个位宽大多数机器上。这足以将格式“ddmmyyyy”的日期存储在单个数字中。我劝你不要使用unsigned int,因为两个日期的差异可能是故意的(例如,如果您不小心将出生日期先放在第一位,而当前日期第二位,则会得到负的年龄,并且检测到您的年龄输入错误)。

#include <stdio.h> 
#include <conio.h> 
int main() // better use int main(), as void main is only a special thing not supported by all compilers. 
{ 
    int a, b, ac, an, c; // drop the "unsigned" here. 
    printf("\n Current date zzllaaaa \n"); 
    scanf("%d", &a); 
    printf("\n Date of birth zzllaaaa \n"); 
    scanf("%d", &b); 
    ac = a % 10000; 
    an = b % 10000; 
    c = ac - an; 
    if (c < 0) 
    { 
     printf("You were born in the future, that seems unlikely. Did you swap the input?\n"); 
    } 
    printf("\n Age is: %d", c); 
    getch(); 
} 
+2

+1,但不要直接提出问题的答案而无需进行单次尝试。 – Gangadhar

+1

@Gangadhar我不同意。我同意接近(这就是我投票的原因),但几乎没有任何努力写下这三条线并帮助某人。这个问题不适合这个平台的要求,但这并不意味着它不应该被回答,如果可能的话。 – stefan

+0

@Downvoter,请留下评论,让我有机会改进我的答案。 – stefan

3

使用模运算符(%)从数字中提取数字。

int date = 12041989; 
int day,month,year; 

year = date%10000; 
date = date/10000; 
month = date/100; 
date = date/100; 
day = date; 
+2

+1,但不要直接提出问题的答案,而无需进行单一尝试。 – Gangadhar

+1

@Gangadhar;同意。但他并没有要求代码。很可能他只想知道如何从数字中提取数字(使用模运算符)。 – haccks