gpt4 book ai didi

c - C 中单词字典顺序排名

转载 作者:行者123 更新时间:2023-11-30 20:35:58 29 4
gpt4 key购买 nike

我尝试根据字典顺序对输入的单词进行排名。但它给出了错误。我认为我在使用该功能时做错了什么。你能告诉我出了什么问题吗?

void rank(char word[][100], int size)
{
int i,j;
char temp[100];
for(i=0;i<size;i++)
for(j=0;j<size;j++)
{
if(strcmp(word[j],word[j+1])>0)
{
strcpy(temp,word[j]);
strcpy(word[j],word[j+1]);
strcpy(word[j+1],temp);
}
}

printf("First word: %s\nLast word: %s",word[0],word[size-1]);
}

int main()
{
char word[100][200];
int i=0;

while(strlen(word[i-1])!=4)
{
printf("enter word: ");
scanf("%s",word[i]);
i++;
}

rank(word,i);
}

最佳答案

这是一些警告和错误。

$ gcc main.c 
main.c: In function ‘main’:
main.c:35:10: warning: passing argument 1 of ‘rank’ from incompatible pointer type [-Wincompatible-pointer-types]
rank(word,i);
^
main.c:5:6: note: expected ‘char (*)[100]’ but argument is of type ‘char (*)[200]’
void rank(char word[][100], int size)

某些数组超出范围:while(strlen(word[i-1])!=4) 工作示例与您的代码类似。我使用 do...while 来解决段错误并调整循环计数器,这样就不会超出范围。

void rank(char word[][200], int size){
char temp[100];
for (int i = 0; i < size - 1; ++i) {
for (int j = i + 1; j < size; ++j) {
if (strcmp(word[i], word[j]) > 0) {
strcpy(temp, word[i]);
strcpy(word[i], word[j]);
strcpy(word[j], temp);
}
}
}
printf("First word: %s\nLast word: %s\n", word[0], word[size - 1]);
}

int main() {
char word[100][200];
int i = 0;
do {
printf("enter word: ");
scanf("%s", word[i]);
i++;

} while (strlen(word[i - 1]) != 4);
rank(word,i);
return (0);
}

测试

 $ ./a.out 
enter word: Superman
enter word: Batman
enter word: Wolverine
enter word: Cyclops
enter word: Thor
First word: Batman
Last word: Wolverine

关于c - C 中单词字典顺序排名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37079515/

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