为什么我的代码错误?我不知道为什么。这个问题是从用户那里获得卡号,并告诉它是有效卡号还是无效卡号。它可以是美国运通卡,万事达卡或Visa卡。美国运通卡有15位数字,必须以34或36开头,而万事达卡有16位数字,可以以51、52、53、54、55开头。Visa卡必须有13或16位数字,并且必须以数字开头。 4.此问题还使用Luhn算法,其中从十位数乘以2来检查卡号是否为每隔2个数字都有效,然后如果不将其乘积加数字再乘以2,那么如果将8乘以2 16,因此您必须加上1 + 6和其他数字。然后,一旦获得总和,就必须将它们加到未乘以2的那些总和中,最后,如果它们的总和可被10整除,则该有效。我真的不知道哪里出问题了,我已经看了将近3个小时的代码。这里也是菜鸟程序员。
#include<stdio.h>
int main(void)
{
//declare and initialize card number
long long number = 0;
//ask user for their credit card number
do
{
printf("Number: ");
scanf("%lli", &number);
}
while (number < 0);
//declare and initialize a counter for the number of the digits
int counter = 0;
long long temp = number;
//loop to count the number of digits
while (temp > 0)
{
temp /= 10;
counter++;
}
//statement for invalid digits
if (counter != 13 && counter != 15 && counter != 16)
{
printf("Invalid number of digits\n");
}
//array to store the digits individually
int digits[counter];
// loop to store the digits in the array
for (int i = 0; i < counter; i++)
{
digits[i] = number % 10;
number /= 10;
}
//loop to multiply every other digit by 2
for (int j = 1; j < counter; j += 2)
{
digits[j] *= 2;
}
// loop to separate then add digits that are greater than 10
for (int x = 1; x < counter; x += 2)
{
if (digits[x] > 10)
{
int s = digits[x] % 10;
digits[x] /= 10;
digits[x] = (digits[x] % 10) + s;
}
}
int sum = 0;
//loop to get the sum of all numbers
for (int y = 0; y < counter; y++)
{
sum += digits[y];
}
sum %= 10;
switch (sum)
{
case '0':
if (counter == 15 && (digits[14] == 3 && (digits[13] == 4 || digits[13] == 7)))
{
printf("American Express\n");
}
else if (counter == 16 && digits[15] == 5)
{
printf("Master Card\n");
}
else if (counter == 13 && digits [12] == 4)
{
printf("Visa\n");
}
else if (counter == 16 && digits[15] == 4)
{
printf("Visa\n");
}
break;
default:
printf("Invalid\n");
break;
}
}
答案 0 :(得分:0)
有三个错误,我很ham愧,花了我很长时间才发现第二个错误。
if (digits[x] > 10)
是一种一次性错误。 Luhn算法的Description而不是大于10,它表示:如果此加倍运算的结果大于9…,则必须为if (digits[x] > 9)
。 / li>
case '0':
必须是case 0:
,因为sum
是整数,而不是字符表示形式。if (counter == 15 && (digits[14] == 3 && (digits[13] == 4 || digits[13] == 7)))
之所以失败,是因为digits
被就地算法修改了,所以7变成了5。我们可以写if (counter == 15 && (digits[14] == 3 && (digits[13] == 4 || digits[13] == 7*2-9)))
代替; else if (counter == 16 && digits[15] == 5)
也是一样。