我正在处理PSET1(CS50)的“信用”任务。我可以使总数对于示例数字正确运行: 4003600000000014 ,但对其他任何数字均无效:
378282246310005作为AMEX
371449635398431作为AMEX
5555555555554444作为万事达卡
4111111111111111作为Visa
我也很难让它成功识别公司。我尝试在其中添加评论。这是link to the assignment。弄清楚我要完成的工作会更好。
#include <cs50.h>
#include <math.h>
#include <stdio.h>
int dubsum;
int singlesum;
int tot;
long secondspot;
int main(void)
{
long number = get_long("Number: ");
//finds every other spot starting at the back and doubling
for (int i = 1; i <= 17; i = i + 2)
{
// front is the string from the starting place of desired number; back truncates behind
long front = pow(10, i + 1);
long back = pow(10, i);
long backsecond = pow(10, i - 1);
long spot = round(((number % front) - (number % back)) / back);
//sanity check 1
// printf("for i: %i,\ndigit to be doubled: %li\n", i, spot);
//if we find a valid 2nd spot #, double it and add together its parts, then reset spot to 0
for (int dub = 2 * spot; spot != 0 && i < 16; spot = 0)
{
//for double digit numbers after doubling
if (dub >= 10)
{
int a = (dub % 100 - dub % 10) / 10;
int b = dub % 10;
dubsum = dubsum + a + b;
}
else
{
dubsum = dubsum + dub;
}
}
// calculating the other numbers
if (i == 1)
{
singlesum = number % back;
}
else
{
secondspot = round(((number % back) - (number % backsecond)) / backsecond);
singlesum = singlesum + secondspot;
}
//sanity check on counters
//printf("digit to be added: %li\nrunning tally for dub sum: %i\n running tally for singlesum: %i\n\n\n", secondspot, dubsum, singlesum);
}
tot = dubsum + singlesum;
printf("%i", tot);
//check on known numbers
if (tot == 20)
{
//AmEx check: 15 digit # starting with 34/37
if (round(number / pow(10, 13)) == 34 || round(number / pow(10, 13)) == 37)
{
printf("AmEx\n");
printf("%f", round(number / pow(10, 13)));
}
//MasterCard check: 16 digt # starting with 51-55, inclusive
if (round(number / pow(10, 14)) >= 51 && round(number / pow(10, 14)) <= 55)
{
printf("Mastercard\n");
}
//Visa Check: 13 || 16 digit # starting with 4
if (round(number / pow(10, 15)) == 4 || round(number / pow(10, 12)) == 4)
{
printf("Visa\n");
}
}
else
{
printf("INVALID\n");
}
}
答案 0 :(得分:0)
由于未使用else if语句和不正确的参数来检查总和,因此拒绝了数字。
//check on known numbers
if (tot % 10 == 0)
{
//AmEx check: 15 digit # starting with 34/37
if (trunc(number / pow(10, 13)) == 34 || trunc(number / pow(10, 13)) == 37)
{
printf("AMEX\n");
}
//MasterCard check: 16 digt # starting with 51-55, inclusive
else if (trunc(number / pow(10, 14)) >= 51 && trunc(number / pow(10, 14)) <= 55)
{
printf("MASTERCARD\n");
}
//Visa Check: 13 || 16 digit # starting with 4
else if (trunc(number / pow(10, 15)) == 4 || trunc(number / pow(10, 12)) == 4)
{
printf("VISA\n");
}
else if (tot % 10 == 0)
{
printf("INVALID\n");
}
}
else
{
printf("INVALID\n");
}