我编写了下面的 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
之前,但事实并非如此。已解决
只需移除
\n
即可修复来自 scanf
.
最佳答案
在 scanf
, 空格字符已经表示任何空格。所以在您的 "%d \n"
该函数已经在最后一位数字之后处理了新行,但随后您强制它等待另一个换行符。
这会导致程序等待另一行。输入后,程序继续并要求搜索号码,此时输入已经输入。
只使用 scanf
中的一个空格,它已经适用于换行符,最好在数字本身之前,这样您就不需要额外的一行来完成操作:
scanf(" %d", arr + i);
关于c - 检查数组中是否存在数字的程序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46040710/