程序冻结 - Luhn算法

时间:2014-02-07 04:07:05

标签: c credit-card luhn

我希望有人可以帮助我。我是一个完整而彻底的C新手。

这是针对C上课程的学校作业(只是简单的旧C,而不是C#或C ++),教授坚持认为我们唯一允许使用的编译器是Borland 5.5。

一般分配是运行可以检查信用卡号有效性的算法。我已成功获取程序来获取用户输入的CC编号,然后将该编号分成数组。它主要打印出我想要的东西。

然而,当我输入最后一个函数(我评论过的那个)然后编译时,程序才开始挂起。我不知道是什么原因引起的。

#include <stdio.h>
#include <math.h>
#include <stdlib.h>

  //global variables declared. 
  //in an earlier version, I was going to use multiple functions, but I couldn't make them work
  float array[16]; 
  double num, ten; 
  int i, a, b, x, y, check; 

int main()
{


  ten = 10; 

  //pick up user-input number
  printf("Enter your credit card number\n>");
  scanf("%lf", &num); 

  //generate the array
  for (i = 15; i >= 0; i--)
    {
      array[i] = fmod(num, ten); 
      num /= 10;
      printf("Array is %1.1lf\n", array[i]);
    }


    //double every other number. If the number is greater than ten, test for that, then parse and re-add. 
    //this is where the program starts to hang (I think). 
  {for (i = 2; i <= 16; i + 2)
    {
      array[i] = array[i] * 2;
        if (array[i] >= 10)
          {
            a = (int)array[i] % 10;
            b = (int)array[i] / 10;
            array[i] = a + b; 
           }
    }
    printf("%f", array[i]); 
    }        

    //add the numbers together
    x = array[2] + array[4] + array[6] + array[8] + array[10] + array[12] + array[14] + array[16];
    y = array[1] + array[3] + array[5] + array[7] + array[9] + array[11] + array[13] + array[15];

    check = x + y;  

    //print out a test number to make sure the program is doing everything correctly. 
    //Right now, this isn't happening
    printf("%d", check);

return 0;


}

2 个答案:

答案 0 :(得分:0)

for (i = 2; i <= 16; i + 2)

应该是

for (i = 2; i <= 16; i = i + 2)

for (i = 2; i <= 16; i += 2)

如你所知,i的值永远不会被修改,所以循环永远不会终止。

答案 1 :(得分:0)

你宣布你的数组

array[16] so array[0] .. array[15]

在第二个for循环中你有

when i = 16 array[16]!

瓦尔特