一、分析程序,写输出结果
1. #include
201709#include
for( m=1; m<=10; m+=2 ) { k = m/3;
for( i=2; i<=k; i++ )
if( m%i ) cout << m << \ } }
解: M的取值为1,3,5,7,9。对应的k的取值为0,1,1,2,3 第二个for循环:只有当k=2和k=3时才执行, 当k=2,i=2,m%i=1为真,输出m为7, 当k=3,i=2,m%i=1为真,输出m为9, 当i=3,m%i=0为假,无输出,结果:7,9
2. #include
void fun(); void main() {int i;
for(i=1;i<5;i++) fun(); cout< void fun() { static int a; int b=2; a += 2 ; cout<< a+b <<'\\t'; } 解:主函数循环4次调用fun(): fun()函数内定义了静态局部变量a,所以a的值会保持到下一次调用, 结果为4 6 8 10 3. #include int fun(int n) { if(n==0) return 1; return 2*fun(n-1); } void main() { int a=5; cout< 解:fun()函数用递归求出2的n次方,结果为32 4. #include void main() { char *cp=\ for (int i=0 ; i<4; i++ ) cout< 解: 主函数4次循环中, 第一次输出cp+i,此时cp指向“word”的第一个字符,所以输出“word”, 之后cp依次往后移一个位置,输出此位置及后面的字符结果为: Word ord rd d 二、根据程序功能填空。 1. 程序把10个数存储到一维数组a中,并求该数组中最大值。 #include int a[10]={76,55,95,87,85,83,65,90,77,85}; int *p= a ; max=*p; for( ; p< &a[10] ; p++) if( *p>max ) max= *p ; cout<<\} 2.下面程序的功能是输出1至100之间每位数字的乘积大于每位数的和的数。例如,45两位 数字的乘积为4×5=20,和为4+5=9。 #include { int n, k=1, s=0, m; for(n=1; n<=100; n++) { k=1; s=0; M=n ; } while( m>0 ) { k*=m; s+=m; m=m/10 ; } if(k>s) cout< } 3.程序对输入的n求s = 1 + 1/23 + 1/33 + … + 1/n3 。 #include {double s; int i, n; cout<<\ s = 0; for (i=1; i 4.函数create从键盘输入整数序列,以输入0为结束。按输入顺序建立单向链表并返回表头。 struct node{int data; node * next;}; node * create() { node *head, *p, *q; p = new node; head = p; cin>>p->data; while( p->data ) { q = p; q= new node ; q->next = p; cin>>p->data; } if (head == p) head = NULL; else q->next = NULL ; free(p) ; return head; } 5.以下程序求方程的全部整数解: 3x + 2y - 7z = 5 ( 0 ≤ x, y, z ≤ 100 ) #include for( x=0; x<=100; x++ ) for( y=0; y<=100; y++ ) { if( ( z=3*x+2*y-5 ) % 7 ) continue ; //求出z的值 z=z/7 ; if( z>0 && z<101 ) //检查z的范围 cout << \ } } 三、程序设计 1. 编写函数 输出以下形状的图形,其中构成图形的数字和输出的行数通过参数传送。 1 2 2 2 3 3 3 3 3 4 4 4 4 4 4 4 答:#include for (i = 0; i < 5; i++) { for (n = 0; n < 2 * i - 1; n++) { cout << i; } cout << endl; } }
相关推荐: