解決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");
}
}
在此先感謝,希望我以正確的方式使用此論壇。
uj5u.com熱心網友回復:
問題就在這里
}else{
//If card number has a length different than 13, 15 or 16
printf("INVALID\n");
}
}短語中的第一個結尾是什么?提示:它與長度無關。建議長度測驗為 if...else if...else if...else; (新的)final else 輸出 INVALID 訊息。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/491762.html
下一篇:R中的條件if陳述句和回圈
