我只是试图用C语言编写线性搜索程序。但是由于某种我不了解的原因,我没有得到预期的输出。请有人解释我做错了什么。
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <stdbool.h>
int main(){
int arr[5];
int query;
bool found = false;
int index;
printf("Insert five elements of your choice: \n");
/*
Getting 5 input from user.
*/
for(int i=0; i<5; i++){
printf("Element %d: ", i+1);
scanf("%d\n", &arr[i]);
}
printf("What number you are looking for: ");
scanf("%d\n", &query);
/*
Checking if the the number is in the array or not!
*/
for(int check=0; check<5; check++){
if(arr[check] == query){
found = true;
index = check;
}
}
if(found){
printf("Result: %d was found in index %d.\n", query, index);
}else
{
printf("Result: Item was not found!");
}
}
答案 0 :(得分:1)
scanf
函数能够读取变量(使用诸如%d
之类的转换说明符),精确符号和任意数量的空格字符。如果您在格式字符串中指定\n
,则scanf
函数将尝试处理任何条您已命中的换行符。您可以通过在\n
调用中从格式字符串中删除scanf
来解决此问题。