C语言程序设计教程 课后习题参考答案 下载本文

return n; }

int lcm(int m, int n) {

return m*n/gcd(m,n); }

(8)

#include

double mypower(double x, int y); main( ) {

double x; int y;

scanf(\

printf(\}

double mypower(double x, int y) {

int i;

double f=1.0;

for(i=1; i<=y; i++) f *= x; return f; }

第7章 1.

(1)6 (2)5 (3)不能 (4)int a[3][2]={{1,2}, {3,4}, {5,6} }; (5)6 9 (6)abc G 2. (1)

#include void reverse( int a[ ], int n ); int main( ) {

int array[10]={0}; int i; printf(“请输入10个整数:”); for( i=0; i<10; i++) scanf(“%d”, &array[i]); reverse( array, 10); //调用函数逆序存储数组中的数据 printf(“逆序后的元素为:\\n”); for( i=0; i<10; i++) printf(“]”, array[i]); printf(“\\n”); return 0; } void reverse( int a[ ], int n ) { int i; int tmp; for( i=0; i

(2)

#include #include

void reverseStr( char str[ ] ); main( ) { char s[100]; gets( s ); reverseStr( s ); puts( s ); }

void reverseStr( char str[ ] ) { int i,j; char t; i=0; j=strlen(str)-1; while( i < j ) { t = str[i];

a[n-i-1] = tmp; str[i] = str[j]; str[j] = t; i++; j--; } }

(3)

#include

int copyTo(int s1[], int n, int s2[ ]); main( ) {

int s1[10], s2[10]; int i,count;

for(i=0; i<10; i++) scanf(\ count = copyTo(s1, 10, s2); for(i=0; i

int copyTo(int s1[], int n, int s2[ ]) {

int i, j=0;

for(i=0; i

return j; }

(4)

#include

void copyToStr(char str1[ ], char str2[ ] ); main( ) {

char s1[100], s2[100]; gets(s1);

copyToStr( s1, s2 ); puts(s2); }

void copyToStr(char str1[ ], char str2[ ] )

{

int i=0,j=0;

while( str1[i] != '\\0' ) { if( str1[i]>='a'&&str1[i]<='z' ) { str2[j] = str1[i]; j++; } i++; }

str2[j] = '\\0'; return j; }

(5)

#include

void deleteAll( char str[ ], char ch); main( ) {

char s[100], ch; gets( s );

ch = getchar( ); deleteAll( s, ch ); puts( s ); }

void deleteAll( char str[ ], char ch) {

int i, j; i = 0; j = 0;

while( str[i] ) { if( str[i] != ch ) { str[j++] = str[i]; } i++; }

str[j] = '\\0'; }

(6)

#include

void replaceAll(char str[ ], int ch1, char ch2); main( ) {

char s[100], c1, c2; gets( s );

c1 = getchar( ); c2 = getchar( );

replaceAll( s, c1, c2 ); puts( s ); }

void replaceAll(char str[ ], int ch1, char ch2) {

int i; i = 0;

while( str[i] ) { if( str[i] == ch1 ) str[i] = ch2; i++; } }

(7)

#include int transformToBin( int dnum, int bin[ ] ) ; int main( ) { int array[32]={0}; //保存转换后的二进制数 int num; //待转换的整数 int cc; //最后得到的二进制总共多少位 printf(“请输入一个整数:”); scanf(“%d”, &num); cc = transformToBin( num, array ); //调用转换函数 cc--; //往回退一个元素下标,使cc指向最后一个元素 for( ; cc>=0; cc-- ) //输出转换后的二进制数 printf(“%d”, array[cc]); printf(“\\n”); return 0; } int transformToBin( int dnum, int bin[ ] )

{