1.
输入一个数n,然后输入n个数,其值各不相同,再输入一个值x,输出这个值在这个数组中的下标志(从0开始,若不在数组中输出-1)
#include<stdio.h>
int main() {
int buf[200];
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%d", &buf[i]);
}
int x;
int ans = -1;
scanf("%d", &x);
for (int i = 0; i < n; i++) {
if (x == buf[i]) {
ans = i;
break;
}
}
printf("%d\n", ans);
}
return 0;
}
2.
输入N个学生的信息,然后进行查询
#include<stdio.h>
#include<algorithm>
#include<string.h>
using namespace std;
struct Student { //用来表示学生个体的结构体
char no[100];
char name[100];
int age;
char sex[5];
bool operator<(const Student & A) const {
//重载小于运算符使其能使用sort函数排序
return strcmp(no, A.no) < 0;
}
}buf[1000];
int main() {
int n;
while (scanf("%d", &n) != EOF) {
for (int i = 0; i < n; i++) {
scanf("%s%s%s%d", &buf[i].no, &buf[i].name, &buf[i].sex, &buf[i].age);
}
sort(buf, buf + n);
int t;
scanf("%d", &t);
while (t-- != 0) {
int ans = -1; //目标元素下标,初始化为-1
char x[30];
scanf("%s", x);
int top = n - 1, base = 0;
//初始时,开始下标为0,结束下标为n-1,查找子集为整个数组
while (top >= base) {//子集不为空重复二分查找
int mid = (top + base) / 2;
int tmp = strcmp(buf[mid].no, x);
if (tmp == 0) {
ans = mid;
break;
}
else if (tmp > 0)
top = mid - 1;
else base = mid + 1;
}
if (ans == -1)
printf("No Answer!\n");
else printf("%s %s %s %d\n", buf[ans].no, buf[ans].name, buf[ans].sex, buf[ans].age);
}
}
return 0;
}