#include#include //查找 int search(int key, int a[], int length); //数组作为函数参数时,往往要用另一个参数传入数组的大小 //不能直接在[]写出数组长度,也不能用sizeof() int main(void) { int a[] ={2,4,6,5,1,3,5,9,11,13,23,14,32};//数组的集成初始化 //int a[13] ={0}; int x; int loc; 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(i=0;i 查找钱数对应的英文表达 线性搜索-遍历 #includestruct#include //线性搜索:遍历 //割裂的结构对cache是不友好的 int search(int key, int a[], int len) { int ret = -1; for(int i=0;i -1) { printf("%sn",name[r]); } return 0; } #include#include struct{ int amount; char *name; }coins[] = { {1,"penny"}, {5,"nickel"}, {10,"dime"}, {25,"quarter"}, {50,"half-dollar"}, }; int main() { int k=25; for(int i=0;i 二分搜索 #include#include //二分搜索 int search(int key,int a[],int len) { int ret = -1; int left=0; int right=len-1; while(right>=left) { int mid=(left+right)/2; if(a[mid] == key){ ret=mid; break; }else if(a[mid] > key) { right=mid-1; }else { left=mid+1; } } return ret; } int main() { int k=55; int a[] = {1,2,35,55,56,63,64,67,78,90}; int c= search(k,a,sizeof(a)/sizeof(a[0])); printf("%d",c); return 0; } 欢迎分享,转载请注明来源:内存溢出
C语言-搜索
查找一个数
赞
(0)
打赏
微信扫一扫
支付宝扫一扫
数数字Digit Counting(Python)
上一篇
2022-12-17
评论列表(0条)