=20)break;cout2.#include"iostream.h"voidmain(){intx;cout>x;if(x==0)coutelsewhile(x!=0){coutx=x/10;}cout}3.#include" />

# c++语言程序设计(龚沛曾 杨志强)实验答案 实验4答案

1.

#include "iostream.h"

void main()

{int n,sum=0;

for(n=1;;sum+=n,n+=2)

if(n>=20) break;

cout<<"sum="<

2.

#include "iostream.h"

void main()

{int x;

cout<<"input x:"<>x;

if(x==0)

cout<<"0";

else

while(x!=0)

{cout<

x=x/10;

}

cout<

}

3.

#include "iostream.h"

void main()

{int i,t=1;

float s=0;

for(i=1;1.0/t>1e-4;i++)

{s=s+1.0/t;

t=t+i;

}

cout<<"s="<

}

4.

#include "iostream.h"

void main()

{double pi=1,t=2;

int n;

for(n=1;t>1e-4;n++)

{pi=pi*t;

t=(float)((2*n)*(2*n))/((2*n-1)*(2*n+1)); }

cout<<"pi="<

}

5.（1）

#include "iostream.h"

#include "iomanip.h"

void main()

{int i,j;

for(i=1;i<=9;i++)

{ cout<

for(j=1;j<=2*i-1;j++)

cout<

cout<

}

}

5.（2）

#include "iostream.h"

#include "iomanip.h"

void main()

{int i,j;

char c;

for(i=9;i>=1;i--)

{ cout<

c=9-i+'A';

for(j=1;j<=2*i;j++)

cout<

cout<

}

}

6.

#include "iostream.h"

void main()

{int m,m1,m2,m3;

for(m=100;m<1000;m++)

{m1=m%10;

m2=m/10%10;

m3=m/100;

if(m1*m1*m1+m2*m2*m2+m3*m3*m3==m) cout<

}

}

7.

#include "iostream.h"

#include "iomanip.h"

void main()

{int x,y,z,k=0;

for(x=1;x<=6;x++)

for(y=x+1;y<=6;y++)

for(z=5;z<=6;z++)

if(x

{ k++;

cout<

}

cout<<"满足条件的方案有："<

}

8.

#include "iostream.h"

#include "stdlib.h"

#include "time.h"

void main()

{int a,n,i,k;

double s=0,temp=0;

srand(time(NULL));

a=rand()%9+1;

n=rand()%6+5;

for(i=1;i<=n;i++)

{temp=temp*10+a;

s=s+temp;

}

cout<<"s="<

}

9.

#include "iostream.h"

#include "math.h"

void main()

{float a,x,x1;

cin>>a;

x=a;

do

{x1=x;

x=2.0/3*x+a/(3*x*x);

}while(fabs(x-x1)>1e-5);

cout<<"编程求得x="<

cout<<"调用函数求得x="<