写一个C++代码:身份证号码n题目描述n十八位居民身份证号码由-6-位地址码、8-位出生日期码、3-位顺序码和-1-位校验码组成倒数第-2-位是性别代码男单女双其格式如图所示。nn1644118823476158398pngn其中校验码的计算方法如下:n1将身份证号码的前-17-位数字分别乘以对应的系数对应关系如下表。-nn号码位nn1nn2nn3nn4nn5nn6nn7nn8nn9nn10nn11nn12nn13nn14nn15nn16nn17nn系数nn7nn9nn10nn5nn8nn4nn
#include
int main() { string id; cin >> id;
// 验证身份证号码是否为18位数字
if (id.size() != 18)
{
cout << "wrong!" << endl;
return 0;
}
for (int i = 0; i < 18; i++)
{
if (id[i] < '0' || id[i] > '9')
{
cout << "wrong!" << endl;
return 0;
}
}
// 计算校验码
int factors[17] = {7, 9, 10, 5, 8, 4, 2, 1, 6, 3, 7, 9, 10, 5, 8, 4, 2};
int sum = 0;
for (int i = 0; i < 17; i++)
{
sum += (id[i] - '0') * factors[i];
}
int remain = sum % 11;
char checkCode;
switch (remain)
{
case 0:
checkCode = '1';
break;
case 1:
checkCode = '0';
break;
case 2:
checkCode = 'X';
break;
case 3:
checkCode = '9';
break;
case 4:
checkCode = '8';
break;
case 5:
checkCode = '7';
break;
case 6:
checkCode = '6';
break;
case 7:
checkCode = '5';
break;
case 8:
checkCode = '4';
break;
case 9:
checkCode = '3';
break;
case 10:
checkCode = '2';
break;
}
if (checkCode != id[17])
{
cout << "wrong!" << endl;
return 0;
}
// 解析出生日期和性别
string address = id.substr(0, 6);
string year = id.substr(6, 4);
string month = id.substr(10, 2);
string day = id.substr(12, 2);
string genderCode = id.substr(16, 1);
string gender;
if (stoi(genderCode) % 2 == 1)
{
gender = "male";
}
else
{
gender = "female";
}
// 输出结果
cout << year << "-" << month << "-" << day << "," << gender << endl;
return 0;
}
原文地址: https://www.cveoy.top/t/topic/p1k 著作权归作者所有。请勿转载和采集!