C编程Luhn算法



我曾尝试用C编写一个程序来检查信用卡的Luhn算法,但它不起作用。我想我不太清楚getchar()是如何工作的,但这个程序对我来说很明智。你能告诉我它出了什么问题吗?提前感谢您在这方面的帮助。

#include <stdio.h>
int main(void) {
char x;
int n, sum, i, c;
sum = 0;
printf("Insert the number of digits: ");
scanf("%d",&n);
printf("Insert the digits: ");
for(i = n; i > 1; i = i - 1){
x = getchar();
if(i%2==0) 
if(2*x < 10) sum = sum + 2*x;
else sum = sum + 2*x - 9;
else sum = sum + x;
i = i - 1;
}
c = (9*sum)%10;
x = getchar();
getchar();
if(x == c) printf("Last digit: %d,nCheck digit: %d,nMatching",x,c);
else printf("Last digit: %d,nCheck digit: %d,nNot Matching",x,c);
}

getchar()读取一个字符。因此,循环中的x = getchar();不好,因为

  • 如果在第一个"后面输入换行符,它首先读取换行符;数字的数目">
  • 它将读取一个字符,而不是一个整数。字符代码通常与字符表示的整数不同,它可能会影响校验位的计算

您应该在循环中执行以下操作,而不是x = getchar();

scanf(" %c", &x); /* ignore whitespace characters (including newline character) and read one character */
x -= '0'; /* convert the character to corresponding integer */
#include <stdio.h>
#define N 16
void luhn_algorithm();
int main(){
int a[N];
int i;
printf("type the card number:n");
for(i=1;i<=N;i++){
scanf("%d",&a[i]);
}
luhn_algorithm(a);
}
void luhn_algorithm(int *a){
int i,multiply=1,m,sum=0,total=0;
for(i=1;i<=N;i++){
if(i%2!=0){
multiply=a[i]*2;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
else if(i%2==0){
multiply=a[i]*1;
if(multiply>9){
while(multiply>0){
m=multiply%10;
sum+=multiply;
multiply/=10;
}
multiply=sum;
}
}
total+=multiply;
}
if(total%10==0){
printf("nthis credit card is valid ");
}
else{
printf("nthis credit card is not valid");
}
}

这是我制作的程序,用来检查信用卡号码是否有效。我把数字放在一个数组中,然后根据它们的位置相乘,如果相加的总数的最后一位是0,那就意味着这张卡是有效的,否则就不是了。检查一下,如果有什么问题,请告诉我。

最新更新