【发布时间】:2023-03-16 05:20:01
【问题描述】:
我编写了下面的 C 代码来检查一个数字是否存在于其元素由用户输入的数组中。但奇怪的是它跳过了第三条printf 语句,直接获取输入并在获取该输入后打印Enter the number you wish to look for。这是什么原因造成的?在代码下方包含输入和输出框。
代码:
#include <stdio.h>
#include <stdlib.h>
void main() {
int arr[30], size, i, num, flag=0;
printf("Enter size of array. \n");
scanf("%d",&size);
printf("Enter %d array elements one by one. \n",size);
for (i=0; i<size; i++) {
scanf("%d \n",&arr[i]);
}
printf("Enter the number you wish to look for. \n");
scanf("%d",&num);
for(i=0;i<size;i++) {
if (num == arr[i]) {
flag++;
}
}
if (flag>0) {
printf("The number %d is present in the array.",num);
} else {
printf("The number %d is not present in the array.",num);
}
}
输入/输出:
Enter size of array.
5
Enter 5 array elements one by one.
1
2
3
4
5
5
Enter the number you wish to look for.
The number 5 is present in the array.
您可以看到Enter the number you wish to look for. 应该在5 之前,但事实并非如此。
已解决
只需从scanf 中删除\n 即可修复。
【问题讨论】:
-
您正在使用 scanf() 没有检查。更加偏执。阅读规范并寻找您没想到的东西。如果您发现了一些,请证明它们不会在您的情况下发生。
-
对不起,我没有得到你的评论。该程序有效,唯一的事情是它首先接受输入,然后打印该行。你能指出为什么会这样吗?再次抱歉。
-
好吧,两个赞成的答案都谈到了您对 scanf() 的使用。问题是您没有预料到的行为。我建议阅读规范并寻找你没想到的东西。您可能会发现这对未来的应用程序很有趣:sekrit.de/webdocs/c/beginners-guide-away-from-scanf.html