我写了这个信用卡验证程序,用户可以输入尽可能多的数据,只要它可以存储在long类型中,使用以下算法:
我的程序使用1-9位数的数字但是一旦我尝试10位数字算法关闭,我不知道我错在哪里,有人可以帮忙吗?同样在if(ccnum <= 4294967295)
中,如果我输入一个大于4294967295的数字,我的程序不会执行else,如果,出了什么问题?
#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;
}
}
答案 0 :(得分:0)
将变量声明为unsigned long long修复了这两个问题
unsigned long long ccnum, num1, num2, even, odd, divisorodd, divisoreven, first, split, check;
double digits;