注意:此处代码可能并非最优化结果,等待代码优化中。。。。
◆1.16② 试写一算法,如果三个整数X,Y和Z
的值不是依次非递增的,则通过交换,令其为
非递增。
要求实现下列函数:
void Descend(int &x, int &y, int &z);
/* 按从大到小顺序返回x,y和z的值 */
void Descend(int &x, int &y, int &z) /* 按从大到小顺序返回x,y和z的值 */ { int temp; if(x<y){temp=x;x=y;y=temp;} if(x<z){temp=x;x=z;z=temp;} if(y<z){temp=y;y=z;z=temp;} }
1.17③ 已知k阶裴波那契序列的定义为
f0=0, f1=0, …, fk-2=0, fk-1=1;
fn=fn-1+fn-2+…+fn-k, n=k,k+1,…
试编写求k阶裴波那契序列的第m项值的函数算法,
k和m均以值调用的形式在函数参数表中出现。
要求实现下列函数:
Status Fibonacci(int k, int m, int &f);
/* 如果能求得k阶斐波那契序列的第m项的值f,则返回OK;*/
/* 否则(比如,参数k和m不合理)返回ERROR */
Status Fibonacci(int k, int m, int &f) /* 求k阶斐波那契序列的第m项的值f */ //没想到m竟然是从0开始的∵ ∵ { int i; long temp; int a[1000]; if(k<=1||m<0){return ERROR;} for(i=0;i<k-1;i++){a[i]=0;} a[i]=1; a[k]=1; for(temp=1,i=k+1;i<=m;++i){ if(temp>MAXINT) return ERROR; temp=temp-a[i-k-1]+a[i-1]; a[i]=temp; } f=a[m]; return OK; }
1.18③ 假设有A、B、C、D、E五个高等院校进行田径对抗赛,
各院校的单项成绩均以存入计算机并构成一张表,表中每一
行的形式为
项目名称 性别 校名 成绩 得分
编写算法,处理上述表格,以统计各院校的男、女总分和团
体总分,并输出。
要求实现下列函数:
void Scores(ResultType *result, ScoreType *score);
/* 求各校的男、女总分和团体总分, 并依次存入数组score */
/* 假设比赛结果已经储存在result[ ]数组中, */
/* 并以特殊记录 {“”, male, ‘ ‘, “”, 0 }(域scorce=0)*/
/* 表示结束 */
相关数据类型定义如下:
typedef enum {female,male} Sex; typedef struct{ char *sport; // 项目名称 Sex gender; // 性别(女:female;男:male) char schoolname; // 校名为’A',’B',’C',’D'或’E’ char *result; // 成绩 int score; // 得分(7,5,4,3,2或1) } ResultType; typedef struct{ int malescore; // 男子总分 int femalescore; // 女子总分 int totalscore; // 男女团体总分 } ScoreType; void Scores(ResultType *result, ScoreType *score) /* 求各校的男、女总分和团体总分, 并依次存入数组score */ /* 假设比赛结果已经储存在result[ ]数组中, */ /* 并以特殊记录 {"", male, ' ', "", 0 }(域scorce=0)*/ /* 表示结束 */ //感觉这道题题意有点模糊.... { int i,j; for(j=0;j<5;++j){ i=0; score[j].malescore=0; score[j].femalescore=0; while(result[i].score!=0) { if('A'+j==result[i].schoolname){ if(male==result[i].gender) score[j].malescore+=result[i].score; if(female==result[i].gender) score[j].femalescore+=result[i].score; } score[j].totalscore=score[j].malescore+score[j].femalescore; ++i; } } }
◆1.19④ 试编写算法,计算i!×2^i的值并存入数组
a[0..ARRSIZE-1]的第i-1个分量中 (i=1,2,…,n)。
假设计算机中允许的整数最大值为MAXINT,则当n>
ARRSIZE或对某个k(1≤k≤n)使k!×2^k>MAXINT时,应
按出错处理。注意选择你认为较好的出错处理方法。
要求实现下列函数:
Status Series(int ARRSIZE, int a[]);
/* 求i!*2^i序列的值并依次存入长度为ARRSIZE的数组a; */
/* 若所有值均不超过MAXINT,则返回OK,否则返回OVERFLOW */
Status Series(int ARRSIZE, int a[]) /* 求i!*2^i序列的值并依次存入长度为ARRSIZE的数组a; */ /* 若所有值均不超过MAXINT,则返回OK,否则返回OVERFLOW */ { int i=1,temp=1; while(i<=ARRSIZE){ if(MAXINT/temp<2*i)return OVERFLOW; temp*=2; temp*=i; a[i-1]=temp; ++i; } return OK; }
◆1.20④ 试编写算法求一元多项式
P(x) = a0 + a1x + a2x^2 + … + anx^n
的值P(x0),并确定算法中每一语句的执行次数和整个算法
的时间复杂度。注意选择你认为较好的输入和输出方法。
要求实现下列函数:
float Polynomial(int n, int a[], float x0);
/* 求一元多项式的值P(x0)。 */
/* 数组a的元素a[i]为i次项的系数,i=0,1,…,n */
float Polynomial(int n, int a[], float x) /* 求一元多项式的值P(x)。 */ /* 数组a的元素a[i]为i次项的系数,i=0,...,n */ { int i=1; float temp=1; float total=a[0]; if(0==n){return total;} while(i<=n){ temp*=x; total+=a[i]*temp; ++i; } return total; }