#include <stdlib.h>
#include <time.h>
#define N 20
void Sort(int a[],int n) {
int i,j,k,t
for(i = 0 i < n - 1 ++i) {
k = i
for(j = i + 1 j < n ++j) {
if(a[k] > a[j]) k = j
}
if(i != k) {
t = a[k]
a[k] = a[i]
a[i] = t
}
}
}
int Find(int a[],int n,int x) {
int low = 0,high = n - 1,mid
while(low <= high) {
mid = (low + high)/2
if(x == a[mid]) return mid
else if(x > a[mid]) low = mid + 1
else high = mid - 1
}
return -1
}
void Show(int a[],int n) {
int i
for(i = 0 i < n ++i) {
printf("%d ",a[i])
}
printf("\n")
}
int main() {
int a[20],i,x,res
srand((unsigned)time(NULL))
for(i = 0 i < N ++i)
a[i] = rand()%N // 每个数都在1 -- 100之间
Show(a,N)
Sort(a,N)
Show(a,N)
x = rand()%100 + 1
res = Find(a,N,x)
if(res >= 0) printf("数值%d的下标为%d。\n",a[res],res)
else printf("数列中没有找到数值%d。\n",x)
return 0
}
#include<stdio.h>int main()
{
int i,res,a[10]={1,4,7,10,13,16,19,22,25,28}
printf("请输入要查找的数:")
scanf("%d",&res)
for(i=0i<10i++)
if(a[i]==res)
break
if(i>=10)
printf("没有要查找元素\n")
else if(i<10)
printf("%d在数组中的位置为:%d,即第%d个数\n",res,i,i+1)
return 0
}
代码时正确的。。。
C语言中的标准函数库中的strchr()函数可以实现查找字符串中的某个字符。C语言strchr()函数:
查找某字符在字符串中首次出现的位置
头文件:#include
<string.h>
strchr()
用来查找某字符在字符串中首次出现的位置,其原型为:
char
*
strchr
(const
char
*str,
int
c)
【参数】str
为要查找的字符串,c
为要查找的字符。
strchr()
将会找出
str
字符串中第一次出现的字符
c
的地址,然后将该地址返回。
注意:字符串
str
的结束标志
NUL
也会被纳入检索范围,所以
str
的组后一个字符也可以被定位。
【返回值】如果找到指定的字符则返回该字符所在地址,否则返回
NULL。
返回的地址是字符串在内存中随机分配的地址再加上你所搜索的字符在字符串位置。设字符在字符串中首次出现的位置为
i,那么返回的地址可以理解为
str
+
i。
提示:如果希望查找某字符在字符串中最后一次出现的位置,可以使用
strrchr()
函数。