c - 检测有效信用卡号算法
问题描述
我刚刚注册了在线 CS50 课程并进行了关于检测有效信用卡号的 pset1。但是,我的算法并没有像我预期的那样运行良好。我使用调试工具逐步查看结果,只要我从 1 运行到 9 的变量它运行良好,所有值都正确添加到总和中。但是当涉及到 i = 10 等等时,numNotSquared 被分配了 -8 并且 numSquared 被分配了 -16 并且它一直这样直到数字结束。请帮我解决这个问题,谢谢。
// Headers and libraries
#include <stdio.h>
#include <cs50.h>
#include <math.h>
int main(void)
{
// Prompt user for card number
long cardNumber = get_long("Enter card number: ");
// Get the length of input
int length = floor(log10(cardNumber)) + 1;
// Range validation
if (length < 13 || length > 16)
{
printf("INVALID\n");
}
int numSquared = 0;
int numNotSquared = 0;
int sum = 0;
// Algorithm to detect valid card
// Based on Luhn's algorithm (https://lab.cs50.io/cs50/labs/2020/x/credit/)
for (int i = 1; i <= length; i++)
{
// If digit is on odd position then mutiply by two
if (i % 2 != 0)
{
{
numSquared = ((int)(cardNumber / pow(10, length - i)) % 10) * 2;
}
// If the total is >= 10, then sum the products' digit
if (numSquared >= 10)
{
sum += ((numSquared % 10) + 1);
}
else
{
sum += numSquared;
}
}
// If digit is on even position then add to the sum
else
{
numNotSquared = (int)(cardNumber / pow(10, length - i)) % 10;
sum += numNotSquared;
}
}
// Find remainder of (total / 10)
if (sum % 10 == 0)
{
if (floor(cardNumber / pow(10, length - 1)) == 4)
{
printf("VISA\n");
}
else
{
int firstTwoDigits = floor(cardNumber / pow(10, length - 2));
if (firstTwoDigits == 34 || firstTwoDigits == 37)
{
printf("AMEX\n");
}
else if (firstTwoDigits == 51 || firstTwoDigits == 52 || firstTwoDigits == 53 || firstTwoDigits == 54 || firstTwoDigits == 55)
{
printf("MASTERCARD\n");
}
}
}
else
{
printf("INVALID\n");
}
}
解决方案
推荐阅读
- r - 如何在 geom_hex 图中将图例中的计数显示为百分比
- html - 纯 HTML 和 CSS 汉堡菜单不起作用
- c# - 如何将 ASP.NET Core Identity 用户作为 EF 迁移的一部分播种
- python - Python BeautifulSoup 提取图像标签
- php - 使用 PHP 从 Google Cloud Bucket 加载图像
- sql - 在 SQL (hive) 中提取数组的最后 N 个元素
- sql - 第二次出现后的 SQL 子字符串
- javascript - 使用 Nodejs 进行异步编程 - 遍历一组链接,打开它们并在完成后将它们保存到 JSON
- c# - HttpClient.SendAsyc() 在生产中返回禁止,但在调试中返回 OK
- angular-material - 如何独立制作动态树视图每个节点