4.1 阅读下列程序,写出执行结果
1.#include <iostream.h>
void main()
{ int i, conut=0, sum=0 ;
float average ;
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;
for( i=0; i<10; i++ )
{ if( a[i] % 2 == 0 ) continue ;
sum += a[ i ] ;
conut ++ ;
}
average = sum / conut ;
cout << "conut = " << conut << '\t' << "average = " << average << endl ;
}
void main()
{ int i, conut=0, sum=0 ;
float average ;
int a[] = { 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 } ;
for( i=0; i<10; i++ )
{ if( a[i] % 2 == 0 ) continue ;
sum += a[ i ] ;
conut ++ ;
}
average = sum / conut ;
cout << "conut = " << conut << '\t' << "average = " << average << endl ;
}
2.#include <iostream.h>
void main()
{ int a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
int *p = a , sum = 0 ;
for( ; p<a+9; p++ )
if( *p % 2 == 0 ) sum += *p ;
cout << "sum = " << sum << endl ;
}
void main()
{ int a[9] = { 1, 2, 3, 4, 5, 6, 7, 8, 9 } ;
int *p = a , sum = 0 ;
for( ; p<a+9; p++ )
if( *p % 2 == 0 ) sum += *p ;
cout << "sum = " << sum << endl ;
}
3.const int n = 5 ;
#include <iostream.h>
#include <iomanip.h>
void main()
{ int a[n][n]={ 0 }, i, j, k ;
#include <iostream.h>
#include <iomanip.h>
void main()
{ int a[n][n]={ 0 }, i, j, k ;
for( k=1 , i=0 ; i<n ; i++ )
for( j=i; j>= 0; j-- , k++ )
a[j][i - j ] = k ;
for( i=0 ; i<n ; i++ )
{ for( j=0; j<n ; j++ )
cout << setw( 3 ) << a[i][j] ;
cout << endl ;
}
}
for( j=i; j>= 0; j-- , k++ )
a[j][i - j ] = k ;
for( i=0 ; i<n ; i++ )
{ for( j=0; j<n ; j++ )
cout << setw( 3 ) << a[i][j] ;
cout << endl ;
}
}
4.int f(int [],int);
#include <iostream.h>
void main()
{ int a[] = { -1, 3, 5, -7, 9, -11 } ;
#include <iostream.h>
void main()
{ int a[] = { -1, 3, 5, -7, 9, -11 } ;
cout << f( a, 6 ) << endl ;
}
int f( int a[], int size )
{ int i, t=1 ;
for( i=0 ; i<size; i ++ )
if( a[i]>0 ) t *= a[i] ;
return t;
}
}
int f( int a[], int size )
{ int i, t=1 ;
for( i=0 ; i<size; i ++ )
if( a[i]>0 ) t *= a[i] ;
return t;
}
5.int f( int [][3], int, int ) ;
#include <iostream.h>
void main()
{ int a[][3] = { 0, 1, 2, 3, 4, 5, 6, 7, 8 } ;
cout << f( a, 3, 3 ) << endl ;
}
int f( int a[][3], int row, int col )
{ int i, j, t=1 ;
for( i=0; i<row; i ++ )
for( j=0; j<col; j++ )
{ a[i][j] ++ ;
if( i == j ) t *= a[i][j] ;
}
return t ;
指针与二维数组 }
指针与二维数组 }
6.#include<iostream.h>
void test1( int *a1 )
{ a1 = new int( 5 ) ;
cout << "*a1 = " << *a1 << endl ;
}
void test2(int * & a2)
{ a2 = new int( 5 ) ;
cout << "*a2 = " << *a2 << endl ;
}
void main()
{ int *p = new int( 1 ) ;
void test1( int *a1 )
{ a1 = new int( 5 ) ;
cout << "*a1 = " << *a1 << endl ;
}
void test2(int * & a2)
{ a2 = new int( 5 ) ;
cout << "*a2 = " << *a2 << endl ;
}
void main()
{ int *p = new int( 1 ) ;
test1( p ) ;
cout << "test1: *p1 = " << *p << endl ;
test2( p ) ;
cout << "test2: *p2 = " << *p << endl ;
}
cout << "test1: *p1 = " << *p << endl ;
test2( p ) ;
cout << "test2: *p2 = " << *p << endl ;
}
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论