C语言编程 找书
答案:2 悬赏:60 手机版
解决时间 2021-01-15 05:21
- 提问者网友:流星是天使的眼泪
- 2021-01-14 12:26
C语言编程 找书
最佳答案
- 五星知识达人网友:笑迎怀羞
- 2021-01-14 14:00
#include
#include
int main(){
long L,k,i,j=-1,weizhi=0,temp,m,t;
printf("请输入书籍数量L和要找的书的索书号k(L>0,k<100000,以逗号隔开):");
scanf("%ld,%ld",&L,&k);
char ai[L*k];
printf("请输入%ld个无重复的整数作为每本书的索书号ai(0 scanf("%s",&ai);
long ailen=strlen(ai);
ai[ailen]=',';
for(i=0;i<=ailen;i++){
if(','==ai[i]){
temp=0;t=1;
weizhi++;
for(m=i-1;m>j;m--,t*=10){
temp+=(ai[m]-'0')*t;}
if(temp==k){
printf("小华要找的书%ld的书位编号是:%ld
",k,weizhi);
break;}
j=i;}}
if(temp!=k){
printf("Error
");}
return 0; }恩,有点复杂,不过你要是把代码搞懂,就代表你可以进入C的高级编程了。
#include
int main(){
long L,k,i,j=-1,weizhi=0,temp,m,t;
printf("请输入书籍数量L和要找的书的索书号k(L>0,k<100000,以逗号隔开):");
scanf("%ld,%ld",&L,&k);
char ai[L*k];
printf("请输入%ld个无重复的整数作为每本书的索书号ai(0 scanf("%s",&ai);
long ailen=strlen(ai);
ai[ailen]=',';
for(i=0;i<=ailen;i++){
if(','==ai[i]){
temp=0;t=1;
weizhi++;
for(m=i-1;m>j;m--,t*=10){
temp+=(ai[m]-'0')*t;}
if(temp==k){
printf("小华要找的书%ld的书位编号是:%ld
",k,weizhi);
break;}
j=i;}}
if(temp!=k){
printf("Error
");}
return 0; }恩,有点复杂,不过你要是把代码搞懂,就代表你可以进入C的高级编程了。
全部回答
- 1楼网友:玩家
- 2021-01-14 15:38
没有编译调试
typedef struct SHELF {
int size;
int count;
int id_list[0];
} Shelf, *ShelfPtr;
int
Shelf_create(Shelf **shelf, int size=100) {
size_t len = sizeof(Shelf) + sizeof(int) * size;
*shelf = (Shelf*)malloc(len);
if (*shelf <= 0) {
return -1;
}
memset(*shelf, 0x00, len);
return 0;
}
int
Shelf_destroy(Shelf **shelf) {
if (*shelf > 0) {
free(*shelf);
*shelf = NULL;
}
return 0;
}
int
Shelf_load(Shelf *shelf) {
int count = 0;
sscanf("input the count of books: ", &count);
if (count <= 0 || count > shelf->size) {
return -1;
}
shelf->count = count;
char buff[1024];
buff[0] = 0x00;
sscanf("input IDs of all the books:", buff);
char *from = *to = buff;
for (int i = 0; i < count; i ++) {
while ((*from < '0' || *from > '9') && *from != 0x00) {
from ++;
}
if (*from == 0x00) {
return -1;
}
while (*to >= '0' && *to <= '9') {
to ++;
}
*to = 0x00;
self->id_list[i] = atoi(from);
}
return 0;
}
int
Shelf_search(Shelf* shelf, int id, int *pos) {
*pos = search(shelf->id_list, 0, shelf->count, id);
return 0;
}
int search(int* list, int from, int to, int value) {
if (from == to) {
return -1;
}
int mid_pos = (from + to) / 2;
int mid_value = list[mid_pos];
if (mid_value == value) {
return mid_pos;
} else if (mid_value < value) {
return search(list, from, mid_pos, value);
} else {
return search(list, mid_pos, to, value);
}
return 0;
}
int main() {
Shelf *shelf = NULL;
Shelf_create(&shelf, 1024);
Shelf_load(shelf);
int id = -1;
int pos = -1;
scanf("input the id to search:", &id);
Shelf_search(shelf, id, *pos);
if (pos >= 0) {
printf("the position of book[%d] is %d ", id, pos);
} else {
printf("the book[%d] is not found ", id);
}
Shelf_destroy(&shelf);
return 0;
}追问你这个好难啊看不懂
我要举报
如以上回答内容为低俗、色情、不良、暴力、侵权、涉及违法等信息,可以点下面链接进行举报!
点此我要举报以上问答信息
大家都在看
推荐资讯