
题目:编写一个函数,输入n为偶数时,调用函数求1/2+1/4+...+1/n,当输入n为奇数时,调用函数
1/1+1/3+...+1/n(利用指针函数)
1.程序分析:
2.程序源代码:
#include "stdio.h"
void main()
{
float peven(),podd(),dcall(); //声明3个float型的函数
float sum; //定义1个float型数
int n; //定义1个int型数
while (1) //进行while循环
{
scanf("%d",&n);// 输入n
if(n>1) //判断n,如果大于1,执行break退出
break;
}
if(n%2==0) //如果n为偶数
{
printf("Even="); //输出Even=
sum=dcall(peven,n); //调用dcall函数
}
else
{
printf("Odd="); //输出Odd=
sum=dcall(podd,n); //虚桥调用dcall函数
}
printf("%f",sum); //输出sum的值
}
float peven(int n) //定义了一个peven函数笑塌
{
float s;
int i;
s=1;
for(i=2;i<=n;i+=2) //进行for循环
s+=1/(float)i; //实现s的累加
return(s); //返回s的值
}
float podd(n) //定义了1个podd函数
int n;
{
float s;
int i;
s=0;
for(i=1;i<=n;i+=2) //进行for循环
s+=1/(float)i; //实现s的累加
return(s); //返回s的值
}
float dcall(fp,n) 定义碰誉圆1个dcall函数
float (*fp)(); 定义1个指针函数
int n;
{
float s;
s=(*fp)(n);
return(s);
}
网上粘来的,其他的注释比较简单,你自己搞定,你自己试试能不能运行出来
C语言程序设计(第7章结构体与共用体)
插入的节点可以在表头、表中或表尾悔铅帆。假定我们激掘按照以学号为顺序建立链表,则插入的
节点依次与表中节点相比较,找到插入位置。由于插入的节点可能在链表的头,会对链表的
头指针造成修改,所以定义插入节点的函数的返回值定义为返回结构体类型的指针。节点的
插入碧雹函数如下:
struct node *insert(head,pstr,n) /*插入学号为n、姓名为pstr的节点*/
struct node *head; /*链表的头指针*/
char *pstr;
int n;
{
struct node *p1,*p2,*p3;
p1=(struct node*)malloc(sizeof(struct node));/* 分配一个新节点* /
strcpy(p1->str,pstr); /* 写入节点的姓名字串*/
p1->num=n; /* 学号*/
p2=head;
if(head==NULL) /* 空表*/
{
head=p1; p1->next=NULL;/*新节点插入表头*/
}
else
{ /*非空表* /
while(n>p2->num&&p2->next!=NULL)
/ *输入的学号小于节点的学号,并且未到表尾* /
{
p3=p2;
p2=p2->next; /* 跟踪链表增长*/
}
if(n<=p2->num) /*找到插入位置*/
if (head==p2) / * 插入位置在表头* /
{
head=p1;
p1->next=p2;
}
else
{ /*插入位置在表中*/
p3->next=p1;
p1->next=p2;
}
else
{ /*插入位置在表尾*/
p2->next=p1;
p1->next=NULL;
}
}
return(head);/* 返回链表的头指针*/
}
#include
#define nmax 100
typedef struct
{
int num;//学号
char name[nmax];//姓名
int escore;//英语成绩
int mscore;//数学成绩
int cscore;//计算机成拍腊绩
}student;
int ascore(student s)//计算总分
{
int sum;
sum=s.cscore+s.escore+s.mscore;
return sum;
}
void sort(student s[],int n)//按总分排序
{
int max=0;
int k=0;
for(int j=0;j
max=ascore(s[j]);k=j;
for(int i=j+1;i
max=ascore(s[i]);k=i;
}
student temp;
temp=s[j];
s[j]=s[k];
s[k]=temp;
}
}
void printstudent(student s)//输出函数
{
printf("%d %s %d %d %d %d",s.num,s.name,s.escore,s.mscore,s.cscore,ascore(s));
printf("\n");
}
void main()
{
student s[3];//我只用三个试试 30个太夸张了
for(int i=0;i<3;i++)
{
printf("输入学生的学号:袭纤滑\n");
scanf("%d",&s[i].num);
printf("输入学生的姓名:\n");
scanf("%s",s[i].name);
printf("输入学生的英语成绩:竖仔\n");
scanf("%d",&s[i].escore);
printf("输入学生的数学成绩:\n");
scanf("%d",&s[i].mscore);
printf("输入学生的计算机成绩:\n");
scanf("%d",&s[i].cscore);
}
sort(s,3);
for(i=0;i<3;i++)printstudent(s[i]);
}