【发布时间】: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