正在加载图片...
return· result omplex& complex operator-( complex& ob)t ∥重载函数:复数减法运算 complex result= new complex( Re-ob. Re, Im-ob. Im ) complex& complex operator ' complex& ob)( ∥重载函数:复数乘法运算 return· result; complex& complex operator / complex&)t ∥重载函数:复数除法运算 double d=ob. Re *ob.Re +ob. Im *ob. Im: complex result= new complex(( Re *ob. Re +Im*ob. Im )/d, Im"ob. Re-Re *ob. Im)/d); return·resl; friend ostream& operator << ostream& os, complex& ob )i ∥友元函数:重载<<,将复数ob输出到输出流对象os中 return o<obR<(ob.加m>=0.0)?“+”:“-”<fabs(ob.m)<“"; 1-7试编写一个函数计算n*2"的值,结果存放于数组 Aarray Size]的第n个数组元素中,0≤ n≤ array Size。若设计算机中允许的整数的最大值为 maxint,则当n> arraySize或者对于某 个k(0≤k≤m),使得k*2k>muxm时,应按出错处理。可有如下三种不同的出错处理方 式: (1)用cerx<及exit(1)语句来终止执行并报告错误 (2)用返回整数函数值0,1来实现算法,以区别是正常返回还是错误返回 (3)在函数的参数表设置一个引用型的整型变量来区别是正常返回还是某种错误返回。 试讨论这三种方法各自的优缺点,并以你认为是最好的方式实现它 【解答】 #include"iostream.h" #define array Sie 100 #define MaxInt Ox7fffffff int calc( int 7 int n)i if(n=0)t for(i=1;i<n;汁+){ 2return *result; } complex& complex :: operator – ( complex& ob ) { //重载函数:复数减法运算 complex * result = new complex ( Re – ob.Re, Im – ob.Im ); return * result; } complex& complex :: operator * ( complex& ob ) { //重载函数:复数乘法运算 complex * result = new complex ( Re * ob.Re – Im * ob.Im, Im * ob.Re + Re * ob.Im ); return *result; } complex& complex :: operator / ( complex& ) { //重载函数:复数除法运算 double d = ob.Re * ob.Re + ob.Im * ob.Im; complex * result = new complex ( ( Re * ob.Re + Im * ob.Im ) / d, ( Im * ob. Re – Re * ob.Im ) / d ); return * result; } friend ostream& operator << ( ostream& os, complex & ob ) { //友元函数:重载<<,将复数 ob 输出到输出流对象 os 中。 return os << ob.Re << ( ob.Im >= 0.0 ) ? “+” : “-” << fabs ( ob.Im ) << “i”; } 1-7 试编写一个函数计算 n!*2n 的值,结果存放于数组 A[arraySize]的第 n 个数组元素中,0  n  arraySize。若设计算机中允许的整数的最大值为 maxInt,则当 n > arraySize 或者对于某 一个 k (0  k  n),使得 k!*2k > maxInt 时,应按出错处理。可有如下三种不同的出错处理方 式: (1) 用 cerr<<及 exit (1)语句来终止执行并报告错误; (2) 用返回整数函数值 0, 1 来实现算法,以区别是正常返回还是错误返回; (3) 在函数的参数表设置一个引用型的整型变量来区别是正常返回还是某种错误返回。 试讨论这三种方法各自的优缺点,并以你认为是最好的方式实现它。 【解答】 #include "iostream.h" #define arraySize 100 #define MaxInt 0x7fffffff int calc ( int T[ ], int n ) { int i, value = 1; if ( n != 0 ) { int edge = MaxInt / n / 2; for ( i = 1; i < n; i++ ) { value *= i*2;
<<向上翻页向下翻页>>
©2008-现在 cucdc.com 高等教育资讯网 版权所有