如何解决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,\nNot Matching",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,则将它们全部相加,这意味着该卡有效,否则无效。 检查一下,如果有什么问题请告诉我。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。