C语言运用结构体 指针函数写一个简单程序 int checkID(char *ID); (7分) 判别身份证校验位是否正确的函数。其中参数 ID 代表一个 18 位身份证号,如果校验位正确,函数返回 1,否则返回 0。
时间: 2024-03-04 10:51:13 浏览: 17
好的,下面是程序的实现:
```c
#include <stdio.h>
#include <string.h>
struct IDInfo {
char province[3];
char city[3];
char county[3];
int year;
int month;
int day;
int order;
char gender;
};
int getCheckCode(const char *ID) {
int factors[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char checkCodes[11] = "10X98765432";
int sum = 0;
for (int i = 0; i < 17; i++) {
sum += (ID[i] - '0') * factors[i];
}
return checkCodes[sum % 11] - '0';
}
struct IDInfo parseID(const char *ID) {
struct IDInfo info;
strncpy(info.province, ID, 2);
info.province[2] = '\0';
strncpy(info.city, ID + 2, 2);
info.city[2] = '\0';
strncpy(info.county, ID + 4, 2);
info.county[2] = '\0';
sscanf(ID + 6, "%4d%2d%2d%3d%c", &info.year, &info.month, &info.day, &info.order, &info.gender);
return info;
}
int checkID(char *ID) {
int checkCode = getCheckCode(ID);
if (ID[17] == checkCode + '0') {
return 1;
} else {
return 0;
}
}
int main() {
char ID[19];
printf("请输入身份证号码:");
scanf("%s", ID);
if (strlen(ID) != 18) {
printf("输入的身份证号码不是18位\n");
return 0;
}
if (checkID(ID)) {
printf("身份证号码校验通过\n");
} else {
printf("身份证号码校验不通过\n");
}
return 0;
}
```
程序中定义了一个结构体 `IDInfo`,用于存储身份证号码中的各个字段。其中,`getCheckCode` 函数计算校验位,`parseID` 函数解析身份证号码中的各个字段,并将其存储到 `IDInfo` 结构体中。`checkID` 函数判断校验位是否正确,如果正确返回 1,否则返回 0。在 `main` 函数中,用户输入身份证号码,程序对其进行校验并输出结果。