C程序设计语言 (第二版) 课后答案第二章

合集下载
  1. 1、下载文档前请自行甄别文档内容的完整性,平台不提供额外的编辑、内容补充、找答案等附加服务。
  2. 2、"仅部分预览"的文档,不可在线预览部分如存在完整性等问题,可反馈申请退款(可完整预览的文档不适用该条件!)。
  3. 3、如文档侵犯您的权益,请联系客服反馈,我们会尽快为您处理(人工客服工作时间:9:00-18:30)。

Exercise 2-1

Write a program to determine the ranges of char , short , int , and long variables, both signed and unsigned , by printing appropriate values from standard headers and by direct computation. Harder if you compute them: determine the ranges of the various floating-point types.

#include

#include

int

main ()

{

printf("Size of Char %d\n", CHAR_BIT);

printf("Size of Char Max %d\n", CHAR_MAX);

printf("Size of Char Min %d\n", CHAR_MIN);

printf("Size of int min %d\n", INT_MIN);

printf("Size of int max %d\n", INT_MAX);

printf("Size of long min %ld\n", LONG_MIN);

printf("Size of long max %ld\n", LONG_MAX);

printf("Size of short min %d\n", SHRT_MIN);

printf("Size of short max %d\n", SHRT_MAX);

printf("Size of unsigned char %u\n", UCHAR_MAX);

printf("Size of unsigned long %lu\n", ULONG_MAX);

printf("Size of unsigned int %u\n", UINT_MAX);

printf("Size of unsigned short %u\n", USHRT_MAX);

return 0;

}

Exercise 2-2

Write a loop equivalent to the for loop above without using && or || .

#include

#define lim 100

void main()

{

int i=0, c;

char s[lim];

while(i

{

c=getchar();

if(c='\n')

break;

if(c= EOF)

break;

++i;

s[i]=c;

}

}

Exercise 2-3

Write the function htoi(s) , which converts a string of hexadecimal digits (including an optional 0x or 0X) into its equivalent integer value. The allowable digits are 0 through 9, a through f, and A through F .

#define YES 1

#define NO 0

int htoi(s[])

{

int a ,I ,b ,n ;

if(s[i]=='0')

{

++i;

if(s[i]=='x'||s[i]=='X')

{

++i;

}

}

n=0;

b=YES;

if( ;b==YES;++i)

{

if(s[i]>='0'&&s[i]<='9')

a=s[i]-'0';

else if(s[i]>='a'&&s[i]<='z')

a=s[i]-'a'+10;

else if(s[i]>='A'&&s[i]<='Z')

a=s[i]-'A'+10;

else

b=NO;

if (b==YES)

n=16*n+a;

}

return n;

}

Exercise 2-4

Write an alternate version of squeeze(s1,s2) that deletes each character in the string s1 that matches any character in the string s2 . void squeeze2(char s1[], char s2[])

{

int i, j, k;

int instr2 = 0;

for(i = j = 0; s1[i] != '\0'; i++)

{

instr2 = 0;

for(k = 0; s2[k] != '\0' && !instr2; k++)

{

if(s2[k] == s1[i])

{

instr2 = 1;

}

}

if(!instr2)

{

s1[j++] = s1[i];

}

}

s1[j] = '\0';

}

Exercise 2-5

Write the function any(s1,s2) , which returns the first location in the string s1 where any character from the string s2 occurs, or -1 if s1 contains no characters from s2 . (The standard library function strpbrk does the same job but returns a pointer to the location.) int any(char s1[], char s2[])

{

int i;

int j;

int pos;

pos = -1;

for(i = 0; pos == -1 && s1[i] != '\0'; i++)

{

for(j = 0; pos == -1 && s2[j] != '\0'; j++)

{

if(s2[j] == s1[i])

{

pos = i;

}

}

}

return pos;

相关文档
最新文档