我很好奇如何在C语言中正确使用%d
。我目前正在学习 C 编程类(class),我们遇到了一个小挑战,要编辑教科书中的代码(C Programming A Modern Approach,K. N. KING)。
目标是从条形码的三个输入端编辑代码:
- 第 1 个数字、第 5 个数字和第 5 个数字最后一个输入,或者
- 一次输入全部 11 位数字。
按照文本解释运算符的方式,我相信 %1d
允许将输入的整数单独分配给相应的变量。
以下是编辑后的代码。
#include <stdio.h>
int main(void)
{
/* 11 integers that come from the bar code of the product,
then 2 intermediate variables for calulation, and lastly the final answer.*/
int d, i1, i2, i3, i4, i5, j1, j2, j3, j4, j5, first_sum, second_sum, total;
printf("Enter the 11 digit Universal Product Code: ");
scanf("%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d%1d", &d, &i1, &i2, &i3, &i4, &i5, &j1, &j2, &j3, &j4, &j5);
// The steps for each calculation from the textbook.
first_sum = d + i2 + i4 + j1 + j3 + j5;
second_sum = i1 + i3 + i5 + j2 + j4;
total = 3 * first_sum + second_sum;
// Prints check digit for given product code.
printf("Check Digit: %d\n", 9 - ((total-1) % 10));
return 0;
}
然而,当我运行该程序(与原始程序同样的麻烦)时,它不接受将 11 位数字输入为 11 个单独的数字,只接受一个大数字。相反,它仍然需要在每个整数后输入。这样可以读取整数并赋值给变量吗?
最佳答案
给定下面的代码,如果您键入“123”然后按回车键,它将打印“1 2 3”。
int main( void )
{
int a, b, c;
printf( "Enter a three digit number\n" );
if ( scanf( "%1d%1d%1d", &a, &b, &c ) != 3 )
printf( "hey!!!\n" );
else
printf( "%d %d %d\n", a, b, c );
}
也就是说 %1d
将一次读取一个数字。
以下示例来自 C11 规范草案的第 7.21.6.2 节
EXAMPLE 2 The call:
#include <stdio.h>
/* ... */
int i; float x; char name[50];
fscanf(stdin, "%2d%f%*d %[0123456789]", &i, &x, name);
with input:
56789 0123 56a72
will assign to i the value 56 and to x the value 789.0, will skip 0123,
and will assign to name the sequence 56\0. The next character read from
the input stream will be a.
一直都是这样,所以如果您的编译器不这样做,您需要获得一个新的编译器。
关于c - 通用产品代码挑战,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28420931/