这一章习题做着很舒服,毕竟很简单。所以很有感觉。

练习 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 <stdio.h>
#include <limits.h>
int main()
{
printf("char max : %d min : %d\n",CHAR_MAX, CHAR_MIN);
printf("unchar max : %u min : %u\n",UCHAR_MAX, );
printf("int max : %d min : %d\n",INT_MAX, INT_MIN);
printf("unsigned int max : %lu min : %d\n",UINT_MAX, );
printf("long max : %ld min : %ld\n",LONG_MAX, LONG_MIN);
printf("unsigned long max : %lu min : %d \n",ULONG_MAX ,); return ;
}

ps :假如unsigned int 最大值不用 %lu 而用 %lld 会导致 后面变量发生无法预知的错误,  %ld 无法装下unsigned int 最大值

练习 2-2

Exercise 2-2 discusses a for loop from the text. Here it is:

 int main(void)
{
/*
for (i = 0; i < lim-1 && (c=getchar()) != '\n' && c != EOF; ++i)
s[i] = c;
*/ int i = ,
lim = MAX_STRING_LENGTH,
int c;
char s[MAX_STRING_LENGTH]; while (i < (lim - ))
{
c = getchar(); if (c == EOF)
break;
else if (c == '\n')
break; s[i++] = c;
} s[i] = '\0'; /* terminate the string */ return ;
}

练习 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 .

 #include <stdio.h>
char A[]; int main(int argc, char const *argv[])
{
scanf("%s", A);
int v = _atoi(A);
printf("%d\n", v);
return ;
} int _atoi(char s[]){
int i, n, hex;
n = ;
for(i=;s[i]>='' && s[i]<='' || s[i]>='a' && s[i]<='z' || s[i]>='A' && s[i] <= 'Z'; ++i){
if(s[i]>='' && s[i]<='')
hex = s[i] - '';
if(s[i]>='a' && s[i]<='z')
hex = s[i] - 'a' + ;
if(s[i]>='A' && s[i]<='Z')
hex = s[i] - 'A' + ;
n = * n + hex;
}
return n;
}

练习 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 

 #include <stdio.h>
#include <string.h>
char a[];
char b[]; int lenth(char b[]);
void strcat_1(char s[], char t[]); int main() {
scanf("%s", a);
scanf("%s", b);
strcat_1(a ,b);
printf("%s", a);
} void strcat_1(char s[], char t[]){
int i, j, k, l, tlen;
tlen = lenth(t);
for(i=;s[i] != '\0';i++){
k=;
if(s[i] != t[k])
continue;
l = i;
while(s[l++] == t[k++]) {
if(t[k]=='\0')
break;
}
if(t[k] == '\0'){
while(s[l-tlen]!='\0'){
s[l-tlen] = s[l];
l++;
}
i+=tlen;
}
}
} int lenth(char b[]){
int i;
for(i=;b[i]!='\0';++i);
return i;
}

Friend 's version

#include <stdio.h>

void squeeze(char s[], char t[]) {
int i, j, k; k = ;
for(i = ; s[i] != '\0'; ++i) {
for(j = ; t[j] != '\0'; ++j) {
if(s[i] == t[j])
break;
}
if(t[j] == '\0')
s[k++] = s[i];
}
s[k] = '\0';
} int main() {
char s[] = "You are e a pig!!!";
char t[] = "Not me";
squeeze(s, t);
printf("%s\n", s);
return ;
}

练习 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.) 

 #include <stdio.h>
#include <string.h>
char s1[];
char s2[]; int any(char s1[], char s2[]){
int i, j, len1, len2;
len1 = strlen(s1);
len2 = strlen(s2);
for(i=;i<len1;++i){
for(j=;j<len2;++j)
if(s1[i] == s2[j])
return i+; }
return -;
} int main(int argc, char const *argv[])
{
int t;
scanf("%s", s1);
scanf("%s", s2);
t = any(s1, s2);
printf("%d\n", t);
return ;
}

练习 2-6

Write a function setbits(x,p,n,y) that returns x with the n bits that begin at position p set to the rightmost n bits of y, leaving the other bits unchanged. 

 #include <stdio.h>
unsigned getbits(unsigned x, int p, int n);
unsigned setbits(int x, int p, int n, int y);
int main(int argc, char const *argv[])
{
unsigned a, y, result;
int b, c, count;
scanf("%d %d %d %d", &a, &b, &c, &y);
//result = getbits(a, b, c);
result = setbits(a, b, c, y);
printf("The result is : %d\n", result);
return ;
} unsigned setbits(unsigned x, int p, int n, int y){
return ( x & ~(~(~ << n) << (p+-n))) | ( (y & ~(~ << n)) << (p+-n) ) ;
} unsigned getbits(unsigned x, int p, int n){
return (x >> (p+-n)) & ~(~ << n);
}

练习 2-7

Write a function invert(x,p,n) that returns x with the n bits that begin at position p inverted (i.e., 1 changed into 0 and vice versa), leaving the others unchanged. 

 #include <stdio.h>
unsigned invert(unsigned x, int p, int n);
int main(int argc, char const *argv[])
{
unsigned a, result;
int b, c, count;
scanf("%d %d %d", &a, &b, &c);
result = invert(a, b, c);
printf("The result is : %d\n", result); return ;
} unsigned invert(unsigned x, int p, int n){
return (x & ~(~(~ << n) << (p+-n))) | (x >>(p+-n) ^ ~(~ << n)) << (p+-n) ;
}

练习 2-8

Write a function rightrot(x,n) that returns the value of the integer x rotated to the right by n bit positions. 

递归法:

 #include <stdio.h>

 void show(unsigned x, int step) {
if(step < )
show(x >> , step + );
printf("%d", x&);
} unsigned rightrot(unsigned x, int n) {
return (x<<(-n))|(x>>n);
} int main() {
unsigned x = ;
show(x, );
printf("\n");
show(rightrot(x, ), );
printf("\n");
return ;
}

练习 2-9

In a two's complement number system, x&=(x-1) deletes the rightmost 1-bit in x . Explain why. Use this observation to write a faster version of bitcount

 #include <stdio.h>

 int bitcount(unsigned x) {
int b; for(b = ; x != ; x >>= )
if(x & )
b++;
return b;
} int bitcount2(unsigned x) {
int b; for(b = ; x != ; x &= (x-))
b++;
return b;
} int main() {
printf("%d, %d\n", bitcount(), bitcount2());
printf("%d, %d\n", bitcount(), bitcount2());
return ;
}

练习 2-10

Rewrite the function lower, which converts upper case letters to lower case, with a conditional expression instead of if-else

 #include <stdio.h>
char A[];
int main(int argc, char const *argv[])
{
int i;
scanf("%s", A);
for(i=;A[i]!=;++i)
A[i] = higher(A[i]);
printf("%s\n", A);
return ;
} int lower(int c){
return c >= 'A' && c <='Z' ? c + 'a' - 'A' : c;
} int higher(int c){
return c >= 'a' && c <='z' ? c + 'A' - 'a' : c;
}

C程序设计语言(第二版)习题:第二章的更多相关文章

  1. CSAPP深入理解计算机系统(第二版)第三章家庭作业答案

    <深入理解计算机系统(第二版)>CSAPP 第三章 家庭作业 这一章介绍了AT&T的汇编指令 比较重要 本人完成了<深入理解计算机系统(第二版)>(以下简称CSAPP) ...

  2. 《数据结构与算法Python语言描述》习题第二章第三题(python版)

    ADT Rational: #定义有理数的抽象数据类型 Rational(self, int num, int den) #构造有理数num/den +(self, Rational r2) #求出本 ...

  3. 《数据结构与算法Python语言描述》习题第二章第二题(python版)

    ADT Date: #定义日期对象的抽象数据类型 Date(self, int year, int month, int day) #构造表示year/month/day的对象 difference( ...

  4. 《数据结构与算法Python语言描述》习题第二章第一题(python版)

    题目:定义一个表示时间的类Timea)Time(hours,minutes,seconds)创建一个时间对象:b)t.hours(),t.minutes(),t.seconds()分别返回时间对象t的 ...

  5. javascrit2.0完全参考手册(第二版) 第2章第2节 语言特性

    脚本执行顺序     js代码是按照它们在html中出现的顺序一行一行被解释的.这表明把函数定义和变量声明放到<head>中会很好.这保证了函数的代码和事件相关的处理程序不会立即执行. 大 ...

  6. python语言程序设计基础(第二版)第五章答案随笔

    1.实现isOdd()函数,参数为整数,如果整数是奇数,返回True,否则返回False def isOdd(num):    if num % 2 == 0:        return True  ...

  7. C++ Primer Plus(第6版)习题(第二章)

    1..编写一个C++程序,它显示您的姓名和地址. #include<iostream> using namespace std; int main() { string name,addr ...

  8. javascrit2.0完全参考手册(第二版) 第1章第2节:javascript的历史和使用

    javascript曾经带给人许多误解,例如如果你不了解它的历史,那么你可能困惑它和java有什么关系,其实它们一点关系都没有.网景公司1995年在Navigator 2.0 中引入这门语言时它叫Li ...

  9. javascrit2.0完全参考手册(第二版) 第2章第4节 基本的数据类型

    每一个变量都有一个确定的类型表明它存储什么样的数据.js基本的数据类型有strings字符串.numbers数字.Booleans布尔类型.字符串是使用双引号或单引号包含的一串字符:数字包括整数或浮点 ...

  10. javascrit2.0完全参考手册(第二版) 第1章第1节 在XHTML文档中增加javascript

    通常,向文档中增加script脚本使用<script>元素,在HTML中增加脚本的方式有4中: (1)放到<script></script>块中: (2)<s ...

随机推荐

  1. quick-cocos2d-x游戏开发【6】——制作您自己的自定义效果button菜单

    前面提到的主菜单使用,还是很easy的,但我们在商业产品.经常看到button他们人很好,照片不仅就好了,和动画也很不错.Candy Crash都玩过吧,他们看到,button.真的像果冻,效果确实非 ...

  2. SQL Server---触发

    今天的第一次SQL Server触发感觉很方便,本文将向您介绍一个简单的SQL Server触发器和简单的使用. 我将确定其.原理.使用细节都是关于. 定义 触发器(trigger)是个特殊的存储过程 ...

  3. 漫游Kafka实战篇clientAPI

    原文地址:http://blog.csdn.net/honglei915/article/details/37697655 Kafka Producer APIs 旧版的Procuder API有两种 ...

  4. [ACM] POJ 3061 Subsequence (仿真足)

    Subsequence Time Limit: 1000MS   Memory Limit: 65536K Total Submissions: 8403   Accepted: 3264 Descr ...

  5. C# 一个WCF简单实例

    以订票为例简单应用wcf 新建一个wcf服务应用程序 在IService1.cs定义服务契约 复制代码 代码如下: namespace WcfDemo { // 注意: 如果更改此处的接口名称 &qu ...

  6. 计算4000000000内的最大f(n)=n值---字符串的问题python实现(五岁以下儿童)

    问题: 写一个函数,计算4 000 000 000 以内的最大的那个f(n)=n的值,函数f的功能是统计全部0到n之间全部含有数字1的数字和.比方:f(13)= 6,由于"1"在& ...

  7. Linux C/C++计划Shell命令大杂烩(1)

    1, 请参见发行信息 cat /etc/issue 2, 查看内核版本号 uname -r 查看内核版本号 uname -p 查看处理器类型32bit/64bit uname -n 查看网络主机名(o ...

  8. Swift语言指南(七)--语言基础之布尔值和类型别名

    原文:Swift语言指南(七)--语言基础之布尔值和类型别名 布尔值 Swift有一个基本布尔类型,叫做布尔(bool),布尔值又称逻辑值(logical),因为它只能为真(true)或假(false ...

  9. 让Docker功能更强大的10个开源工具

    让Docker功能更强大的10个开源工具 更好的管理.Web前端程序.更深入地了解容器应用程序,Docker生态系统正在迅速发展,这还得归功于其充满活力的开源社区. 软件项目的成功常常根据其催生的生态 ...

  10. BAT 特殊符号总结

    原文:BAT 特殊符号总结 BAT特殊符号总结,用好特殊符号,利用提高开发效率.^ 转义符 用在特殊符号之前 比如: echo 非常^&批处理 如果不加^ 那么"批处理"将 ...