【发布时间】:2021-03-18 17:39:51
【问题描述】:
我尝试编写一个程序来使用函数和数组来查找最短和最长的字符串,但程序不起作用。程序不显示订购的功能。 这是我的代码:
#include<stdio.h>
#include<string.h>
void Max(char x[][1000], int n);
void Min(char x[][1000],int n);
void Max(char x[][1000], int n){
int i,Max,len1,c;
Max=strlen(x[0]);
for(i=1;i<n;i++){
len1=strlen(x[i]);
if(len1>Max)
{
c=i;
Max=len1;
}
}printf("\nthe longest string among all is \"%s\" \n \n",x[c]);
}
void Min(char x[][1000],int n){
int i,min,len2,d;
min=strlen(x[0]);
for(i=1;i<n;i++){
len2=strlen(x[i]);
if(len2<min)
{
d=i;
min=len2;
}
}
printf("\n the shortest string among all is \"%s\" \n \n",x[d]);
}
int main(){
int i,jmlh=0,n,z;
printf("How many name to accept: ");
scanf("%d",&n);
char x[n][1000];
printf("\nEnter %d words: \n");
for(i=0;i<=n;i++){
gets(x[i]);
}
Max(x,n);
Min(x,n);
return 0;
}
输入是
3
然后输入:
robin van persie
lionel messi
ronaldo
应该是这样的输出:
the longest string among all is "robin van persie".
the shortest string among all is "ronaldo".
也许有人想帮助我修复这个程序,我真的需要你的意见。谢谢
【问题讨论】:
-
你没有初始化 c 或 d。请阅读您的编译器警告并修复它们
-
请注意 The
gets()function is so dangerous that it should never be used! 它不再是标准 C 的一部分。任何教你使用它的老师都需要回去重新学习补救(现代)C。当然,使用char x[n][1000];给出了一个数组足够大,您不太可能遇到溢出,但即使数组的大小也不能消除这种可能性。 -
函数
Max()和Min()应该更相似(len1与len2,也不需要c与d;Max与min在函数中),两个函数都不应该打印任何东西。相反,函数应该返回最长或最短字符串的索引,调用代码 (main()) 应该处理打印。将 I/O(打印)与“计算”分开是良好编程的基本技术。它使计算在其他程序中更接近可重用——这还不是你的主要关注点,但随着时间的推移它会成为一个。 -
在函数中使用函数名作为变量名也不是一个特别好的主意——即使目的是确保递归是不可能的。您在函数
Max()中有一个局部变量Max— 您的皮肤应该会爬行,就好像有虫子试图爬过它一样。 -
我的 min 函数是否正确会产生最短的字符串?我不确定我的程序
标签: c max min c-strings strlen