C++程序设计 张耀仁 练习第6章

来源:互联网 发布:mac修改照片的拍摄时间 编辑:程序博客网 时间:2024/06/03 19:40

1、写一个Sum()的函数,它可以指定要累加的数字的数量,并把结果传回来。

 #include <iostream>
#include <new>
using namespace std;
int S_Sum(int b);
int main ()
{
 
 int x,y;
 cout <<"输入数量"<<endl;
 cin >>x;
 y = S_Sum (x);
 cout << "输入的数字相加的和是:"<<y<<endl;
 return 0;
}

int S_Sum(int b)
{
 int a=0;
 
 for ( int c=0;c<b;c++)
 {
  cout <<"输入第"<<c+1<<"个数字"<<endl;
  int *PV= new int(sizeof(int));
  cin >> *PV;
  a+= *PV;
  delete PV;

 }

 return a;
}

 

 

 

 

 

 

2、(1)写一个程序,它包括两个分别叫做Square()和Cubic()的inline 函数,以自动产生下列对照表(各行都是整数):

 

 

N         N^2       N^3
----------------------------------------
      0      0      0
      5     25    125
10   100          1000
15   225          3375
20   400          8000
25   625          15625
30   900          27000
35   1225         42875
40   1600         64000
45   2025         91125
50   2500         125000
----------------------------------------

 

 

 

其中Square()用来计算输入值的平方,而Cubic 用来计算输入值的三次方.

(2)、在函数Square()和Cubic中分别加入一个static 变量(各叫做CountSquare和CountCubic),让各函数能够计算被调用的次数。

 

#include <iostream>
#include <iomanip>
int  Sum_CountSquare;
int  Sum_CountCubic;
using namespace std;
inline int Square(int a)
{   int b;
    int static CountSquare=0;
    b=a*a;
 ++CountSquare;
 Sum_CountSquare=CountSquare;
 return b;
 
}

 

inline int Cubic(int d)
{
 int e;
    int static CountCubic=0;
  e=d*d*d;
  ++CountCubic;
     Sum_CountCubic=CountCubic;
 return e;

}

int main ()
{
 cout <<setw(10)<<left<<'N';
 cout <<setw(10)<<left<<"N^2";
 cout <<setw(10)<<left<<"N^3"<<endl;
  cout <<"----------------------------------------"<<endl;
 for (int c=0;c<=5;c=c+5)
 {
       cout<<setw(7)<<right<<c;
    cout<<setw(7)<<right<<Square(c);
    cout<<setw(7)<<right<<Cubic(c)<<endl;
 }
 for (int e=10;e<=50;e=e+5)
 {
  cout <<setw(5)<<left<<e;
  cout <<setw(13)<<left<<Square(e)<<Cubic(e)<<endl;;
  
 }
 cout <<"----------------------------------------"<<endl;

 cout <<"函数Square被调用次数是:"<<Sum_CountSquare<<'/n'<<"函数Cubic被调用次数是:"<<Sum_CountCubic<<endl;
 return 0;
}

 

 

 

            

 

原创粉丝点击