1.常见的解决方案 知识点备注: ‘1’ - ‘0’ = 1 具体事例分析:
char str[10] = “12345”; ‘1’ - ‘0’ = 1; 1 * 10 + ‘2’ - ‘0’ = 12; 12 * 10 + ‘3’ - ‘0’ = 123; 123 * 10 + ‘4’ - ‘0’ = 1234; 1234 * 10 + ‘5’ - ‘0’ = 12345;
身份证检验案例:
#include<stdio.h>
int main(){
char idArray[18]; // 存储身份证前18位id
printf("input your id:");
gets(idArray); // 接收输入的身份证信息
int ratioId[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
char check[11] = {'1', '0', 'X', '9', '8', '7', '6', '5', '4', '3', '2'};
int i, sum = 0;
for(i = 0; i < 17; i++){
sum += (idArray[i] - '0')*ratioId[i]; //对前17位数字加权求和,这里的idArray[i] - '0'实现的是数字字符向整型数字的转变
}
if(idArray[17] == check[sum % 11]){
printf("身份证合法~");
} else{
printf("身份证不合法~");
}
return 0;
}
实验结果:
|