【发布时间】:2020-03-31 09:58:52
【问题描述】:
为什么我的代码错了??不知道为什么...这个问题是从用户那里获取一个卡号,并判断它是有效的卡号还是无效的卡号。它可以是美国运通卡、万事达卡或维萨卡。美国运通卡有 15 位数字,必须以 34 或 36 开头,而万事达卡有 16 位数字,可以以 51、52、53、54、55 开头。Visa 卡必须有 13 位或 16 位数字,并且必须以4. 这个问题还使用了 Luhn 算法,其中检查卡号是否有效,从十位开始每隔一个数字乘以 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;
}
}
【问题讨论】:
-
一个想法是,当您想将数字作为数字序列处理时,C 字符串(即数字字符序列)比 C 整数更匹配。
-
您能否在代码输出错误的情况下添加预期输出示例?
-
编号:378282246310005 AMEX 编号:2221000000000009 MASTERCARD developer.paypal.com/docs/payflow/payflow-pro/… 我使用该链接获取测试编号