gpt4 book ai didi

c - 检查函数返回值A,但在main中,发现值为-1

转载 作者:太空宇宙 更新时间:2023-11-04 07:53:44 25 4
gpt4 key购买 nike

错误似乎在 binarySearch 函数及其所在的 for 循环中。我放置了一些 printf 来检查值。 binarySearch 应该返回值:8,但 for 循环中的索引变量为 -1。

如果格式看起来很糟糕,我深表歉意。请指导我如何在此处发布漂亮的代码。

非常感谢!

#include <stdio.h>
#include <string.h>

int binarySearch(char[][7], char[], int, int);
void deleteAndMoveEntry(char[][7], int, int);

int main() {
// all the variables
const int MAXIMUM = 5000;
char temp[7];
char symbol[MAXIMUM][7];
int sizeSymbol = 0, sizeDeleted = 0;
char toDelete[MAXIMUM][7];
int i = 0, j;
int index;
FILE *in = fopen("stockin.txt", "r");
FILE *deleted = fopen("stockdel.txt", "r");
FILE *out = fopen("stockout.txt", "w");
FILE *errorFile = fopen("error.txt", "w");

while (fscanf(in, "%s\n", temp) == 1 && i < MAXIMUM) {
strcpy(symbol[i], temp);
i++;
sizeSymbol++;
}

i = 0;

while (fscanf(deleted, "%s\n", temp) == 1 && i < MAXIMUM) {
printf("Hi\n");
strcpy(toDelete[i], temp);
i++;
sizeDeleted++;
}
// Should we sort array symbol? To implement later for fun

for (i = 0; i < sizeDeleted; i++) {
index = binarySearch(symbol, toDelete[i], 0, sizeSymbol);
printf("%d\n", index);

if (index != -1) {
deleteAndMoveEntry(symbol, index, sizeSymbol);
sizeSymbol--;
} else if (index == -1)
fprintf(errorFile, "%s\n", toDelete[i]);
}

for (i = 0; i < sizeSymbol; i++)
fprintf(out, "%s\n", symbol[i]);

fclose(in);
fclose(out);
fclose(deleted);
fclose(errorFile);
return 0;
}

int binarySearch(char symbol[][7], char toFind[], int left, int right) {
if (right >= left) {
int mid = left + ((right - left) / 2);
if (strcmp(toFind, symbol[mid]) == 0) {
printf("%d\n", mid);
return mid;
}

if (strcmp(toFind, symbol[mid]) < 0)
binarySearch(symbol, toFind, left, mid - 1);

if (strcmp(toFind, symbol[mid]) > 0)
binarySearch(symbol, toFind, mid + 1, right);
}
return -1;
}

void deleteAndMoveEntry(char symbol[][7], int index, int size) {
int i;
for (i = index; i < size - 1; i++) {
strcpy(symbol[i], symbol[i + 1]);
}

strcpy(symbol[i + 1], "");
}

最佳答案

问题很可能是由于缺少return引起的递归调用中的语句。换行

  if (strcmp(toFind, symbol[mid]) < 0)
binarySearch(symbol, toFind, left, mid - 1);

if (strcmp(toFind, symbol[mid]) > 0)
binarySearch(symbol, toFind, mid + 1, right);

  if (strcmp(toFind, symbol[mid]) < 0)
return binarySearch(symbol, toFind, left, mid - 1);

if (strcmp(toFind, symbol[mid]) > 0)
return binarySearch(symbol, toFind, mid + 1, right);

没有那些return语句,执行落到函数的底部,返回值为 -1,这解释了您在 main 中观察到的行为.

关于c - 检查函数返回值A,但在main中,发现值为-1,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52022520/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com