【发布时间】:2022-08-10 00:12:56
【问题描述】:
解决后CS50 学分问题集,我唯一的问题是卡号4062901840, 没有通过测试。运行 check50 说输入这个数字后,它应该打印“无效”(这是正确的,是一个 10 位数字)但是而是打印 \" \".
已经使用 10 位数字运行了 20 次测试,并且所有 20 次都正确通过了测试,代码非常简单,因为我尝试只使用到目前为止我们所学的内容并且不使用数组或其他库。您能否指出正确的方向以了解为什么会发生这种情况?
程序应该要求一个数字,并评估它是否符合 luhn 算法,即:
-
从数字的开始,每隔一个数字乘以 2 倒数第二个数字,然后将这些产品的数字相加。
-
将总和与未乘以 2 的数字的总和相加。
-
如果总数的最后一位数字是 0(或者,更正式地说,如果总数 模 10 等于 0),数字有效!
-
之后,程序应该检查卡号是amex、visa、mastercard还是无效的
每种卡类型的条件是:
-美国运通(15 位数字) 从 34 或 37 开始
-万事达卡(16 位数字) 从 51、52、53、53 或 55 开始
签证(13 位或 16 位数字) 从 4 开始
这是我的代码
#include <cs50.h>
#include <stdio.h>
诠释主要(无效) {
long cnum, cnumClone;
int count, first, tempo, sum = 0;
do{
printf(\"Enter card number\\n\");
scanf(\"%ld\", &cnum);
} while(cnum == 0);
// Clones card number to manipulate it through the iteration
cnumClone = cnum;
//Count every digit of the entered card number
for(count = 1; cnumClone != 0; count++)
{
//Get the last digit
tempo = cnumClone % 10;
//Remove last digit
cnumClone /= 10;
//Select digits to be multiplied
if(count % 2 == 0)
{
tempo *= 2;
//In case the product is a 2 digit number
if (tempo >=10)
{
tempo = tempo % 10;
tempo += 1;
sum += tempo;
}else{
//Add to the sum
sum += tempo;
}
}else{
//Add to the sum directly if it wasn´t a every other digit
sum += tempo;
}
}
//Last step of Luhn´s algorithm
if (sum % 10 == 0)
{
//Since count initiates on 1 for iteration purposes, take away 1
count -= 1;
// If card number length is 16 checks if it´s a mastercard or visa
if(count == 16)
{
first = cnum / 100000000000000;
if(first == 51 || first== 52 || first == 53 || first == 54 || first == 55)
{
printf(\"MASTERCARD\\n\");
}else{
first = first /10;
if(first == 4)
{
printf(\"VISA\\n\");
}else{
printf(\"INVALID\\n\");
}
}
}
// If card number length is 15 checks if it´s an amex
if(count == 15)
{
first = cnum / 10000000000000;
if(first == 34 || first == 37)
{
printf(\"AMEX\\n\");
}else{
printf(\"INVALID\\n\");
}
}
// If card number length is 15 checks if it´s a visa
if (count == 13)
{
first = cnum / 1000000000000;
if(first == 4)
{
printf(\"VISA\\n\");
}
}
}else{
//If card number has a length different than 13, 15 or 16
printf(\"INVALID\\n\");
}
}
在此先感谢,希望我以正确的方式使用此论坛。
标签: if-statement cs50