一、题目描述:
身份证号的校验身份证号码共18位,最后一位是校验位A[17]
aaaaaabbbbbbbbcccd 校验的规则是如下:
前十七位的权值分别是:W[17]:7 9 10 5 8 4 2 1 6 3 7 9 10 5 8 4 2
x=(A[0]*W[0]+A[1]*W[1]+…+A[16]*W[16])mod11
x和校验位y的对应规则如下:
x:0 1 2 3 4 5 6 7 8 9 10
y:1 0 x 9 8 7 6 5 4 3 2
若y等于d则身份证号码正确
二、输出格式:
身份证号码正确
身份证号码不正确
三、输出样例:
52242619811105565x正确
五、解决方法:
(1)思路:
- 验证输入身份证是否18位
- 身份证校验位的校验
(2)代码实现:
#include <iostream>
#include <cstring>
#include <algorithm>
using namespace std;
int main()
{
int W[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'};
char A[18]={'0'}; //check和A都是char类型
cin>>A;
//验证输入的身份证号是否为18位,strlen函数
int num=strlen(A);
if(num !=18) cout<<A<<"不正确";
//计算前17位权值
//要进行加权,所以A本是字符,所以要转化成数字,ASCII要减去48,也可写成 (int)A[i]-'0' ,字符'0'对应的ASCII就是48
int sum=0;
for(int i=0;i<17;i++)
sum+=int(A[i]-48)*W[i];
int x=sum%11; //x和y时计算得来 正确的
char y=check[x]; //y与身份证最后一位是否相等,相等输出:身份证号正确,不相等输出:正确身份证号错误
if(check[x]==A[17]){
cout<<A<<"正确"<<endl;
system("pause");
return 0;
}else{
for(int i=0;i<17;i++)
cout<<A[i];
cout<<y<<"错误"<<endl;
system("pause");
return 0;
}
}