c - 从 8 位整数中提取年份 (ddmmyyyy)

标签 c

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

编辑:根据你告诉我的,我是这样做的:(我必须通过输入当前日期和他的出生日期来计算一个人的年龄)

#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。这是为什么?

最佳答案

如果您不关心年份中有 5 位或更多位数字的日期,您可以使用模运算符:

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

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

#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();
}

关于c - 从 8 位整数中提取年份 (ddmmyyyy),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19343838/

相关文章:

c - 单核 OpenMP

C:如何用指针数组生成固定数量的对象

c - K&R 1.21,打印数组时插入新行

c - 如何将用户输入限制为预定数量的整数

c++ - CUDA 时间事件

c - 不使用tail实现函数

C - 反转句子 - 递归 - 无数组

c - PostgreSQL PQgetvalue : array return

c - Linux 原始套接字 - ip header 中的字节顺序

c - 线程亲和性也限制内存分配?