【问题标题】:Leading Zeros used in intint 中使用的前导零
【发布时间】:2019-04-14 19:44:03
【问题描述】:

我正在尝试完成一个程序,但是当它被读取为 int 时,前导零会被删除。如果用户在开始时输入零,我需要这个前导零,因为我在程序的后面使用它来做数学运算,不能只在 printf 中添加前导零。

printf("Enter the first 6 digits of the barcode: \n");
scanf("%i", &n1);
printf("Enter the first 6 digits of the barcode: \n");
scanf("%i", &n2);

//Splits number1 into individual digits
   count1 = 0;
   while (n1 != 0){
       array1[count1] = n1 % 10;
       n1 /= 10;
       count1++;
   }

   count2 = 0;
   while (n2 > 0){
       array2[count2] = n2 % 10;
       n2 /= 10;
           count2++;
//Steps 1-3
int sumo = array1[5]+array1[3]+array1[1]+array2[5]+array2[3]+array2[1]; //adds odd
int sume = array1[4]+array1[2]+array1[0]+array2[4]+array2[2]; //adds even without 12
int sumd = 3*sumo; //multiplies odds
int sum  = sume+sumd; //adds above and evens
int chec = sum%10;
int check = 10-chec;

整个程序可以在here找到

【问题讨论】:

  • 所以,使用字符串进行扫描......
  • 你需要使用%d来扫描一个十进制整数,而不是%i。特别是当它有前导零时。
  • 带有前导零的%i序列被扫描为八进制数字,这意味着0149将被扫描为12。甚至没有 149。而且绝对没有前导零!忘掉%i,总是错的。

标签: c arrays int modulo leading-zero


【解决方案1】:

当您将值存储为整数时,前导零总是会丢失,因此您需要将值存储为其他值(可能是字符串)

【讨论】:

    【解决方案2】:

    您应该将输入扫描为字符串而不是 int。您可以稍后使用 atoi 将其更改为 int(用于计算总和)。

    【讨论】:

    • You can later change it to int using atoi 你又丢失了前导零。
    • 没有直接的方法将前导零添加到int,这就是为什么有人建议使用可以保持前导零完整的字符串。我建议使用atoi 进行这种操作array1[5]+array1[3]+array1[1]+array2[5]+array2[3]+array2[1];
    • 他为什么不能直接添加代表数字的ASCII值?
    • 他可以,但最终他需要int 的值,对吧?
    • 根据我读过的内容,我需要使用 atoi,然后将其转换回 int,然后再进行 sum 等数学运算。
    【解决方案3】:

    int 中使用的前导零

    首先,通过以下方式改进代码:

    1. 检查scanf()的返回值。

    2. 十进制输入可能出现前导零时,请务必使用"%d" 而不是"%i"。对于"%i",前导 0 表示 八进制 输入。 @Antti Haapala。仅此更改就需要帮助 OP。

      "%d" "012" --> 12 decimal
      "%d" "078" --> 78 decimal
      "%i" "012" --> 10 decimal
      "%i" "078" --> 7 decimal, with "8" left in stdin 
      

    找到领先的'0' 的各种方法如下:


    要计算输入的字符数,请使用"%n" 记录int 之前和之后的扫描位置。 "%n"scanf() 的返回值没有贡献。

    int n1;
    int offset1, offset2; 
    if (scanf(" %n%d%n", &offset1, &n1, &offset2) == 1) {
      int width = offset2 - offset1;
      printf("%0*d\n", width, n1);
    }
    

    这会计算 字符 而不仅仅是 digits,因为 "+123" 的宽度为 4。


    更强大的方法是将输入读取为字符串,然后对其进行处理。

    // printf("Enter the first 6 digits of the barcode: \n");
    char buf[6+1];
    if (scanf(" %6[0-9]", buf) == 1) {
      int n1 = atoi(buf);
      int width = strlen(buf);
      printf("%0*d\n", width, n1);
    }
    

    【讨论】:

      猜你喜欢
      • 2014-10-23
      • 2011-10-09
      • 1970-01-01
      • 2019-10-05
      • 2023-01-18
      • 1970-01-01
      相关资源
      最近更新 更多