int中使用的前导零

时间:2018-11-12 05:04:04

标签: c arrays int modulo leading-zero

我正在尝试完成一个程序,但是当它作为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

3 个答案:

答案 0 :(得分:2)

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

答案 1 :(得分:0)

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

答案 2 :(得分:0)

  

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'的各种方法如下:


要计算输入的字符数,请使用int记录"%n"前后的扫描位置。 "%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);
}

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


一种更强大的方法是将输入作为 string 读取,然后对其进行处理。

// 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);
}
相关问题