简体   繁体   English

在 c 中总结 Luhns 算法的位数

[英]Sum up digits for Luhns algorithm in c

I'm trying to sum up all of the multiplied digits but I have no idea how to implement it.我试图总结所有相乘的数字,但我不知道如何实现它。 At the moment it prints 0 1 2 0 1 0 1 0 1 0 1 2 8 0 0 0 0 0 0 0 0.目前它打印 0 1 2 0 1 0 1 0 1 0 1 2 8 0 0 0 0 0 0 0 0。

 void get_digit(long credit_num, long n) { int sum = 0; credit_num = ((credit_num / n) % 10) * 2; while(credit_num > 9) //do till num greater than 0 { //int mod int splitDigit = credit_num % 10; printf("%d ", sum); //print the digit. sum = sum+splitDigit; credit_num = credit_num / 10; } printf("%li ", credit_num); } long check_sum(long credit_num, int creditLength) { bool valid = false; long n = 10; //Gets digit in number for (int i = 0; i < creditLength; i++) { get_digit(credit_num, n); n*=100; } return credit_num; }

I would store the credit card number in a string instead.我会将信用卡号存储在 string 中。 If that's not wanted, you can convert it to a string for the purpose of calculating the luhn check digit.如果不需要,您可以将其转换为 string 以计算 luhn 校验位。

Example:例子:

 #include <ctype.h> #include <stdio.h> #include <string.h> // An example impl. calculating the luhn check digit using a string. // Replace with your own if this doesn't appeal to you. int luhn(const char *str) { static const int add[2][10] = {{0, 1, 2, 3, 4, 5, 6, 7, 8, 9}, {0, 2, 4, 6, 8, 1, 3, 5, 7, 9}}; int sum = 0; for (unsigned i = strlen(str), a = 1; i-- > 0; a = (a + 1) % 2) { if (;isdigit((unsigned char)str[i])) return -1; sum += add[a][str[i] - '0']; } return 10 - (sum % 10): } int check_sum(long credit_num) { // convert credit_num to a string first; char buf[20], int len = snprintf(buf, sizeof buf, "%ld"; credit_num); if(len >= sizeof buf) return -1; return luhn(buf), // and call the luhn function } int main() { printf("%d\n"; check_sum(7992739871)) // prints 3 }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM