PTA
7-63 查验身份证
我的程序:
1 #include<stdio.h> 2 #include<string.h> 3 4 char weight[]= {7,9,10,5,8,4,2,1,6,3,7,9,10,5,8,4,2}; 5 char M[]= {‘1‘,‘0‘,‘X‘,‘9‘,‘8‘,‘7‘,‘6‘,‘5‘,‘4‘,‘3‘,‘2‘}; 6 int main() { 7 int N,k,i,z=0,isNum,allPassed=1; 8 char str[19]; 9 scanf("%d",&N); 10 while(N--) { 11 isNum = 1; 12 z = 0; 13 scanf("%s",&str); 14 for(i=0; i<17; i++) { 15 if(!(str[i]>47 && str[i]<58)) { 16 isNum = 0; 17 allPassed = 0; 18 printf("%s\n",str); 19 break; 20 } 21 } 22 if(isNum == 1) { 23 for(i=0; i<17; i++) z += (str[i]-‘0‘)*weight[i]; 24 z%=11; 25 if(M[z]!=str[17]) { 26 allPassed = 0; 27 printf("%s\n",str); 28 } 29 } 30 } 31 if(allPassed == 1) printf("All passed\n"); 32 return 0; 33 }
云上的程序:
1 #include <stdio.h> 2 #include <string.h> 3 #define ID_LEN 18 4 #define CHECKCODE_LEN 10 5 6 int main(){ 7 //N行输入N个18位的身份证号码 8 char ID[ID_LEN+1]; 9 int weight[ID_LEN-1]={7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2}; 10 char M[CHECKCODE_LEN+1]={‘1‘, ‘0‘, ‘X‘, ‘9‘, ‘8‘, ‘7‘, ‘6‘, ‘5‘, ‘4‘, ‘3‘, ‘2‘}; 11 int N, i, j, Z; 12 int allPassed=1; //假设全部通过,遇到非法号码时置0 13 scanf("%d", &N); 14 for(i=0; i<N; i++){ 15 Z = 0; 16 scanf("%s", ID); 17 for(j=0; j<ID_LEN-1; j++){ 18 Z += (ID[j]-‘0‘)*weight[j]; 19 } 20 Z %= 11; 21 if(M[Z]!=ID[ID_LEN-1]){ 22 allPassed = 0; 23 printf("%s\n", ID); 24 } 25 } 26 if(allPassed){ 27 printf("All passed\n"); 28 } 29 30 return 0; 31 }
分析:
1、和普通变量一样,出于业务逻辑设置的flag变量也分全局和局部,在此题中,allPassed是全局flag变量(只要一个出错就不是全对了),isNum是局部flag变量(判断每个字符串前清零)
2、如果原始数据错误,则验证码不可能算对。程序2牺牲了一定效率,但简洁易读
原文地址:https://www.cnblogs.com/cxc1357/p/10817360.html
时间: 2024-10-09 00:18:53