【发布时间】:2015-02-25 01:27:24
【问题描述】:
我编写了这个信用卡验证程序,用户可以输入任意多的 didigts,只要它可以存储在 long 类型中,使用以下算法:
- 取从最右边开始的数字中的所有其他数字并将它们加在一起,num1
- 然后将其余未相加的数字加倍,然后拆分数字并将它们相加。前任。如果我们有 9 作为数字之一,我们会将其加倍为 18,然后将其拆分为 1 和 8,然后将它们相加 1+8=9 等等,num2
- 然后我们将 num1 和 num2 相加,如果结果数字以 0 结尾,比如 50,则卡片有效,如果以非零结尾,则卡片无效
我的程序适用于 1-9 位数字,但一旦我尝试 10 位数字,算法就会关闭,我不确定我错在哪里,有人可以帮忙吗?同样在if(ccnum <= 4294967295) 中,如果我输入一个大于 4294967295 的数字,我的程序不会执行 else if,这是怎么回事?
#include <iostream>
#include <cmath>
using namespace std;
int main ()
{
unsigned long ccnum;
int num1, num2, even, odd, divisorodd, divisoreven, first, split, check;
double digits;
cout << "Enter your credit card number: ";
cin >> ccnum;
digits = ceil(log10((double)ccnum + 1));
if (ccnum <= 4294967295){
num1 = 0;
num2 = 0;
divisorodd = 100;
divisoreven = 10;
first = ccnum % 10;
for (int i = 0; i <= digits; i++){
odd = ((ccnum / divisorodd) % 10);
num1 = num1 + odd;
divisorodd = divisorodd * 100;
}
num1 = num1 + first;
for (int i = 0; i <= digits; i++){
even = ((ccnum / divisoreven) % 10) * 2;
split = (even % 10) + ((even / 10) % 10);
num2 = num2 + split;
divisoreven = divisoreven * 100;
}
}
else if (ccnum > 4294967295){
cout << "\nIncorrect credit card number.\n";
}
cout << "\nNum1 is: " << num1 << "\n";
cout << "\nNum2 is: " << num2 << "\n";
check = num1 + num2;
cout << "\nThe check number is: " << check << "\n";
if (check % 10 == 0){
cout << "\nThe credit card number is valid! Thank you.\n" << endl;
}
else if (check % 10 != 0){
cout << "\nThe credit card number is invalid! Sorry.\n" << endl;
}
}
【问题讨论】:
-
unsigned long在 Windows 上是 32 位,最大值为 4294967295。当您尝试存储更大的数字时,您希望发生什么?ccnum <= 4294967295总是为真,所以else永远不会执行。 -
另外,信用卡号是一串数字。它是 not 一个整数 - 不要这样对待它。 Here 是验证信用卡号的算法。
-
为了解决问题,它必须被视为整数而不是字符串,问题指出用户只能输入一个可以存储在 long 类型中的数字,所以我该如何解决所以 else 执行?
-
@JoaoDias 使用 64 位整数,例如
unsigned long long。 -
long在任何给定平台上仅保证为 32 位。任何告诉您信用卡号可以放入long的人都大错特错。如果你坚持使用整数,可以使用uint64_tfrom<stdint.h>。
标签: c++