Luhn算法(模10算法)检验银行卡号正确性

中文描述:
1、从卡号最后一位数字开始,偶数位乘以2,如果乘以2的结果是两位数,将结果减去9。
2、把所有数字相加,得到总和。

3、如果信用卡号码是合法的,总和可以被10整除。

英文描述

1.Counting from the check digit, which is the rightmost, and moving left, double the value of every second digit.
2.Sum the digits of the products (e.g., 10: 1 + 0 = 1, 14: 1 + 4 = 5) together with the undoubled digits from the original number.
3.If the total modulo 10 is equal to 0 (if the total ends in zero) then the number is valid according to the Luhn formula; else it is not valid.

代码

C++:
char digit;
int oddLengthChecksum=0;
int evenLenthChecksum=0;
int position =1;
cout<<"Enter a number:";
digit=cin.get();
while(digit != 10)
{
if(position%2==0)
{
oddLengthChecksum+=doubleDigitValue(digit-'0');
evenLengthChecksum+=digit-'0';
}
else {
oddLengthChecksum+=digit-'0';
evenLenthChencksum+=doubleDigitValue(digit-'0');
}
digit=cin.get();
position++;
}
int checksum;
//对输入的标识号长度进行奇偶检查
if((position-1)%2==0) checksum=evenLenthChecksum;
//position-1 原因:前段使用cin.get()函数,最后一个字符是表示结束的行末符
else checksum=oddLengthChecksum;
cout<<"Checksum is"<
if(checksum%10==0)
{
cout<<"Checksum is divisible by 10. Valid.\n";
}
else { cout<<"Checksum is not divisible by 10. Invalid. \n"}

你可能感兴趣的:(Luhn算法(模10算法)检验银行卡号正确性)