C ++信用卡验证问题

时间:2015-02-25 01:27:25

标签: c++

我写了这个信用卡验证程序,用户可以输入尽可能多的数据,只要它可以存储在long类型中,使用以下算法:

  • 从最右边开始,将数字中的所有其他数字加在一起,将它们加在一起,num1
  • 然后取出未添加的其余数字并将其加倍,然后拆分数字并将其相加。恩。如果我们将其作为数字9中的一个,我们将其加倍为18,然后将其拆分为1和8并将它们加1 + 8 = 9等,num2
  • 然后我们拿num1和num2并将它们加在一起,如果结果数字以零结尾,比如50,那么该卡有效,如果它以任何其他结束,那么它为零无效

我的程序使用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;
    }

}

1 个答案:

答案 0 :(得分:0)

将变量声明为unsigned long long修复了这两个问题

unsigned long long ccnum, num1, num2, even, odd, divisorodd, divisoreven, first, split, check;
double digits;