Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

c语言查找某个元素在数组中位置 #157

Open
jeffsui opened this issue Jan 12, 2022 · 0 comments
Open

c语言查找某个元素在数组中位置 #157

jeffsui opened this issue Jan 12, 2022 · 0 comments
Labels

Comments

@jeffsui
Copy link
Owner

jeffsui commented Jan 12, 2022

#include <stdio.h>
int search(int key,int a[],int length);
int main(void){
	int loc;
    int a[]={2,4,6,7,9,11,13,23,14,32};
    //printf("%d\n", sizeof(a));
    //printf("%d\n", sizeof(a[0]));
    int x;
    printf("请输入一个数字:");
    scanf("%d", &x);
    loc = search(x, a, sizeof(a)/sizeof(a[0]));
    if (loc != -1)
    {
        printf("%d在索引为%d的位置上\n", x, loc);
    }else{
        printf("%d不存在\n",x);
    }
	return 0;
} 

int search(int key,int a[],int length){
	int ret = -1;
	int i;
	for(int i=0;i<length;i++){
		if(a[i] == key){
			ret = i;
			break;
		}
	}
	return ret;
}
@jeffsui jeffsui added the c label Jan 12, 2022
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
Projects
None yet
Development

No branches or pull requests

1 participant