题目要求:输入一行字符,将其中最长的单词输出。
#include
int main()
{ void f(char s[]);
char s[100];
printf("enter a sentence:");
scanf("%s",s);
f(s);
}
void f(char s[])
{
int i,n,m=0,sum=0,temp=0;
for(n=0;s[n+m]!='\0';n++)
{ for(i=0;s[m+n+i]!=' ';i++)
sum=sum+i;
if(i>m) {temp=m+n;m=i;}
}
for(n=temp;n<=temp+m;n++)
printf("%c",s[n]);
}
int main()里的void f(char s[]);移到int main()上面就对了。
// app2.cpp : Defines the entry point for the console application.
//
#include "stdafx.h"
#include <stdio.h>
void f(char s[]);
int main()
{
char s[100];
printf("enter a sentence:");
gets(s);
f(s);
return 0;
}
void f(char s[])
{
int max = 0;
int maxpos = 0;
int curr = 0;
int i = 0;
while (s[i] != '\0')
{
if (s[i] == ' ')
{
curr = 0;
}
else
{
curr++;
if (curr > max)
{
max = curr;
maxpos = i - curr + 1;
}
}
i++;
}
for (i = 0; i < max; i++)
printf("%c", s[maxpos + i]);
printf("\n");
}
enter a sentence:an apple fall down from a big yello tree
apple
Press any key to continue
回复louiset: 使用前先声明,所以要放到前面去,规范一些的做法是将方法声明到头文件里,然后包含这个头文件