C if()中的每个条件都独立工作,但当我将数字添加到if()以确认输入为15位时,它会中断

C if()中的每个条件都独立工作,但当我将数字添加到if()以确认输入为15位时,它会中断,c,C,if()中的每个条件都独立工作,但当我将“数字”添加到if()以确认输入是15位数字时,它会中断 int main(void) { long x = get_long("card number?\n"); //Luhn's algorithm for 15 digit CC //find even digits of CC int a = (((x/10) % 10)*2); int b = (((x/1000) % 10)*2); int

if()中的每个条件都独立工作,但当我将“数字”添加到if()以确认输入是15位数字时,它会中断

int main(void) {
  long x = get_long("card number?\n");
     
  //Luhn's algorithm for 15 digit CC
  //find even digits of CC
  int a = (((x/10) % 10)*2);
  int b = (((x/1000) % 10)*2);
  int c = (((x/100000) % 10)*2);
  int d = (((x/10000000) % 10)*2);
  int e = (((x/1000000000) % 10)*2);
  int f = (((x/100000000000) % 10)*2);
  int g = (((x/10000000000000) % 10)*2);
  //sum digits of products
  int h = ((a / 10) % 10) + (a % 10) + ((b / 10) % 10) + (b % 10) + ((c / 10) % 10) + (c % 10) + ((d / 10) % 10) + (d % 10) + ((e / 10) % 10) + (e % 10) + ((f / 10) % 10) + (f % 10) + ((g / 10) % 10) + (g % 10);
  //int i is the final sum for Luhn's algorithm  
  int i = h + (x % 10) + ((x/100) % 10) + ((x/10000) % 10) + ((x/1000000) % 10) + ((x/100000000) % 10) + ((x/10000000000) % 10) + ((x/1000000000000) % 10) + ((x/100000000000000) % 10);

  //digit counting loop
  int digits = 0;
  do {
      digits++;
      x /= 10;
  } while(x != 0);

  //american express if statement... [15 digits, starts with 3, sum of Luhn's algo ends in zero]     
  if (digits == 15 && (x / 100000000000000) % 10 == 3 && i % 10 == 0) {
    printf("American Express\n");
  } else {
    printf("invalid\n");
  }
}

如果我正确读取了您的代码,我认为您正在覆盖
x
的原始值。具体来说,这一行:
x/=10重新分配给x,但当您检查此处的第一个数字
(x/1000000000000)%10==3
时,您假设x没有变化。循环将以
x==0
退出,但是
(x/1000000000000)%10==3
将始终失败,因为左侧始终为0。要解决这个问题,只需在while循环之前将卡号存储在另一个变量中,比如插入
longcard\u number=x位于do语句上方。然后在下面的
if
中,将
x
替换为
卡号

优异点。听起来是这样的。有没有一种方法可以在不覆盖x的情况下运行do while循环?更新了答案,建议@dylanflynn考虑从一个循环开始,该循环将数字存储在数组中,同时计算数字。