t = t + 10;
} else
cout << \你算错了!\}
cout << \你的成绩是:\分\} }
int Rand(int m, int n) {
static int r;
//静态变量保留上一个随机数
do
{
r = ( 25173*r + 13849 ) % 65536 ; } while (r
}
5.已知勒让德多项式为:
?1p)??n(x?x??((2n?1)pn?1(x)?(n?1)pn?2(x))/n编写程序,从键盘输入x和n的值,使用递归函数求pn(x)的值。 【解答】
#include
cout << \ cin >> x >> n;
cout << \}
double p( double x,int n ) { double t1,t2; if( n == 0 )
return 1; else
if( n == 1 )
return x;
else {
t1 = ( 2*n-1 )*p( x,n-1 );
t2 = ( n-1 )*p( x,n-2 );
return ( t1-t2 )/n;
n?0n?1n?1 }
}
6.把以下程序中的print()函数改写为等价的递归函数。
#include
for( int i = 1; i <= w; i ++ ) {
for( int j = 1; j <= i; j ++ ) cout << i << \cout << endl; } } int main() {
print( 5 );
}
程序运行结果:
1 2 2 3 3 3 4 4 4 4
5 5 5 5 5
【解答】
#include
void main() {
print( 5 );
{ print( w-1 );
for( i=1; i<=w; i++ )
cout << w << \ \ cout << endl; }
}
n?1h(f(a)?f(b))?hf(a?ih),其中,h = ( b?a ) / n,n为积7.已知用梯形法求积分的公式为:Tn?2i?1?分区间的等分数,编程求如下积分的值。要求:把求积分公式编写成一个函数,并使用函数指针作为形式
参数。调用该函数时,给出不同的被积函数作为实际参数求不同的积分。 ①
?01?x2dx ② ?1#include
1421?xdx ③
2??2sinxdx0
【解答】
#include
return 4 / ( 1 + x*x ); }
double f2( double x ) {
return sqrt( 1 + x*x ); }
double f3( double x ) {
return sin( x ); }
double trap( double( *fun )( double x ), double a,double b,long n ) {
double t,h; int i;
t = ( ( *fun )(a) + ( *fun )( b ) ) / 2.0; h = ( b - a ) / n;
for( i=1; i<=n-1; i++ ) t += ( *fun )( a + i * h ); t *= h; return t; } int main() {
double t1,t2,t3; t1 = trap( f1,0,1,10000 ); cout << \ t2 = trap( f2,1,2,10000 ); cout << \ t3 = trap( sin,0,3.14159265/2,10000 ); cout << \
}
8.编写一个程序,包含三个重载的display函数和一个主函数。要求:第一个函数输出double值,前面用字符串―a double:‖引导;第二个函数输出一个int值,前面用字符串―a int:‖引导;第三个函数输出一个char字符值,前面用字符串―a char:‖引导;在主函数中,分别用double、int和char型变量作为实参调用display函数。 【解答】
#include
{
cout << \ }
void display( int i ) {
cout << \ }
void display( char c ) {
cout << \ } int main() {
double d = 1.5; int i = 100; char c = 'a'; display( d ); display( i ); display( c );
}
9.使用重载函数编程序分别把两个数和三个数从大到小排列。 【解答】
#include
sort( 5.6, 79 ); sort( 0.5, 30.8, 5.9 ); }
void sort(double x,double y) {
if ( x>y )
cout << x << '\\t' << y << endl;
else
cout << y << '\\t' << x << endl; }
void sort( double x,double y,double z ) { double t;
if( y cout << x << '\\t' << y << '\\t' << z << '\\t' << endl; } n10.给定求组合数公式为:Cm?m!n,编一程序,输入m和n的值,求Cm的值。注意优化算 n!(m?n)!法,降低溢出可能。要求:主函数调用以下函数求组合数: int Fabricate( int m, int n ); Fabricate函数内需调用Multi函数: int Multi( int m, int n ); 和Multi函数的定义。 【解答】 n 分析计算公式Cm? n//返回Cm的值 // 返回 m?(m?1)?…?n 程序由4个文件组成。头文件用于存放函数原型,作为调用接口;其他3个cpp文件分别是main、Fabricate m!得到: n!(m?n)!m!/(n!*(m-n)!)=(m*(m-1)*…*(m-n+1)*(m-n)!)/ (n!*(m-n)!) =(m*(m-1)*…*(m-n+1)/ (n!) 因此可以避免求较大数据m的阶乘,减少溢出的可能性。 //Fabricate.h #ifndef FABRICATE_H #define FABRICATE_H int Fabricate( int m,int n ); int Multi( int m, int n ); #endif //main.cpp #include cout << \ cin >> m >> n; cout << \} //Fabricate.cpp #include \int Fabricate( int m, int n ) { return Multi( m, m-n + 1 ) / Multi( n, 1 ); } //Multi.cpp int Multi( int m, int n ) { int i, t = 1; for( i=n; i<=m; i++ ) t = t * i;