例6.8 输入一行字符,统计其中有多少个单词,单词之间用空格分隔开。 编写程序:
#include
char string[81];
int i,num=0,word=0; char c;
gets(string); // 输入一个字符串给字符数组string for (i=0;(c=string[i])!='\\0';i++) // 只要字符不是'\\0'就继续执行循环 if(c==' ') word=0; // 如果是空格字符,使word置0 else if(word==0) // 如果不是空格字符且word原值为0 {word=1; // 使word置1 num++; // num累加1,表示增加一个单词 }
printf(\ //输出结果 return 0; }
例6.9 有3个字符串,要求找出其中最大者。 编写程序: #include
char str[3][20]; // 定义二维字符数组
char string[20]; // 定义一维字符数组,作为交换字符串时的临时字符数组 int i;
for (i=0;i<3;i++)
gets (str[i]); // 读入3个字符串,分别给str[0],str[1],str[2] if (strcmp(str[0],str[1])>0) // 若str[0]大于str[1] strcpy(string,str[0]); // 把str[0]的字符串赋给字符数组string else // 若str[0]小于等于str[1] strcpy(string,str[1]); // 把str[1]的字符串赋给字符数组string if (strcmp(str[2],string)>0) // 若str[2]大于string
strcpy(string,str[2]); // 把str[2]的字符串赋给字符数组string printf(\ // 输出string return 0; }
例7.1 输出以下的结果,用函数调用实现。 ****************** How do you do! ****************** 编写程序:
#include
{void printstar(); void print_message(); printstar(); print_message(); printstar(); return 0; }
void printstar() {
printf(\}
void print_message() {printf(\ How do you do!\\n\}
例7.2 输入两个整数,要求输出其中值较大者。要求用函数来找到大数。 编写程序:
#include
{ int max(int x,int y); int a,b,c;
printf(\ scanf(\ c=max(a,b);
printf(\}
int max(int x,int y) // 定义max函数 {
int z; // 定义临时变量
z=x>y?x:y; // 把x和y中大者赋给z
return(z); // 把z作为max函数的伦值带回main函数 }
例7.3将例7.2稍作改动,将在max函数中定义的变量z改为float型。函数返回值的类型与指定的函数类型不同,分析其处理方法。 编写程序:
#include
{int max(float x,float y); float a,b; int c;
scanf(\ c=max(a,b);
printf(\ return 0; }
int max(float x,float y)
{float z; z=x>y?x:y; return(z); }
例7.4 输入两个实数,用一个函数求出它们之和。 编写程序: 程序1:
#include
{float add(float x, float y); float a,b,c;
printf(\ scanf(\ c=add(a,b);
printf(\ return 0; }
float add(float x,float y)
{float z; z=x+y; return(z); }
程序2:
#include
float add(float x,float y)
{float z; z=x+y; return(z); }
void main() {
float a,b,c;
printf(\ scanf(\ c=add(a,b);
printf(\}
相关推荐: