[英]Program not proceeding after taking array input in C
#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d ", &a[i]);
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
當我運行代碼時,我只能輸入數組的元素,因此程序不會繼續進行。 代碼有什么問題?
int n,a[n],element;
相當於說
int n;
int a[n];
int element;
注意到什么了嗎? 您正在聲明一個具有未初始化變量n
的可變大小數組。 這會導致意外行為。 在設置 n 的值后聲明你的數組!
int n,element;
scanf("%d", &n);
int a[n];
在觀察你的代碼時,
#include<stdio.h>
int main(){
printf("Enter the size of array: ");
int n,a[n],element;
scanf("%d", &n);
printf("Enter the elements of array in ascending order\n");
for(int i=0; i<n; i++){
scanf("%d", &a[i]); // correction: here you had given space after %d...
}
printf("Enter the element to be searched: ");
scanf("%d", &element);
int low = 0;
int high = n-1;
int mid = (low+high)/2;
int flag = 0;
while(low<=high){
if(a[mid]==element){
flag =1;
break;
}
if(a[mid]<element){
low = mid + 1;
}
else{
high = mid -1;
}
}
if(flag){
printf("%d found", element);
}
else{
printf("Not found");
}
return 0;
}
你給了空間scanf("%d ", &a[i]);
在不應該使用的%d
之后,這就是為什么你的程序在輸入數組后沒有繼續運行......我假設你的二進制搜索操作是正確的並且工作正常......
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.