该程序采用两个数字(每个数字两位)作为输入。然后,它获取第一个条目的第二个数字,并将其与第二个条目的第一个字符配对。
示例输入:
89 43
输出:
94
(9 是第一个数字的第 2 位数字,4 是第二个数字的第 1 位数字)。我知道如何扫描整数的第一个数字,但我似乎不知道如何扫描第二个数字。
编辑:这就是我陷入困境的地方:
int a,b;
scanf("%d %1d",&a,&b);
printf("%d %d",a,b);
最佳答案
program is taking two numbers (two digits each) as input
scan the 2nd digit of an integer
以 1 位数进行扫描并不是实现最终目标的有效方法。只需扫描2 int
s,测试是否 < 100
然后使用 /10
和%10
提取数字。
这种方法更容易检测和处理错误输入。
int a,b;
if (scanf("%d %d",&a,&b) != 2) puts("Bad input");
else if (a < 10 || a >= 99 || b < 10 || b > 99) puts("Input out of range");
else {
printf("%d %d --> ",a,b);
printf("%d%d\n",a%10,b/10);
}
<小时/>
如果代码想要处理前导零,代码可以在带有 fgets()
的行中读取然后通过各种方式进行解析。坚持scanf()
,代码可以使用"%n"
记下扫描偏移。
int n1,n2,n3,n4=0;
if (scanf(" %n%d%n %n%d%n",&n1,&a,&n2, &n3,&b,&n4) != 2) puts("Bad input");
else if (n2-n1 != 2 || a < 0 || n4-n3 != 2 || b < 0) puts("Input out of range");
else {
/* as above */
}
注意:这仍然不会标记像 "+3 -0"
这样的输入一样糟糕。
关于c - 扫描整数的第 2 位数字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52613608/