The C programming language (second edition,KR) exercise(CHAPTER 3)

news2025/9/18 0:44:39

      E x c e r c i s e 3 − 1 Excercise\quad 3-1 Excercise31:输出结果如图1所示,这里故意让二分搜索算法去寻找一个在数组中不存在在的数,然后去看两种二分搜索算法分别所花费的时间的大小,为了使得所花费的时间更具有可分辨性,这里让搜索过程重复执行了 100000000 100000000 100000000次。

/* Solution by Paul Griffiths (mail@paulgriffiths.net) */

/*
  
  EX3_1.C
  =======

  Suggested solution to Exercise 3-1

*/

#include <stdio.h>
#include <time.h>

int binsearch(int x, int v[], int n);     /*  Original K&R function  */
int binsearch2(int x, int v[], int n);    /*  Our new function       */

#define MAX_ELEMENT 200000


/*  Outputs approximation of processor time required
    for our two binary search functions. We search for
    the element -1, to time the functions' worst case
    performance (i.e. element not found in test data)   */

int main(void) 
{
    int testdata[MAX_ELEMENT];
    int index;                  /*  Index of found element in test data  */
    int n = -1;                 /*  Element to search for  */
    int i;
    clock_t time_taken;

    /*  Initialize test data  */
    
    for ( i = 0; i < MAX_ELEMENT; ++i )
        testdata[i] = i;
    
    
    /*  Output approximation of time taken for 100000000 iterations of binsearch() */
    
    for ( i = 0, time_taken = clock(); i < 100000000; ++i ) 
	{
        index = binsearch(n, testdata, MAX_ELEMENT);
    }
    time_taken = clock() - time_taken;
    
    if ( index < 0 )
        printf("Element %d not found.\n", n);
    else
        printf("Element %d found at index %d.\n", n, index);
    
    printf("binsearch() took %lu clocks (%lu seconds)\n",
           (unsigned long) time_taken,
           (unsigned long) time_taken / CLOCKS_PER_SEC);
    
    
    /*  Output approximation of time taken for 100000000 iterations of binsearch2() */
    
    for ( i = 0, time_taken = clock(); i < 100000000; ++i ) 
	{
        index = binsearch2(n, testdata, MAX_ELEMENT);
    }
    time_taken = clock() - time_taken;
    
    if ( index < 0 )
        printf("Element %d not found.\n", n);
    else
        printf("Element %d found at index %d.\n", n, index);
    
    printf("binsearch2() took %lu clocks (%lu seconds)\n",
           (unsigned long) time_taken,
           (unsigned long) time_taken / CLOCKS_PER_SEC);
    
    return 0;
}


/* binsearch:find x in v[0] <= v[1] <= ... v[n-1] */

int binsearch(int x, int v[], int n) 
{
    int low, mid, high;
    
    low = 0;
    high = n - 1;
    while ( low <= high ) 
	{
        mid = (low+high) / 2;
        if ( x < v[mid] )
            high = mid - 1;
        else if ( x > v[mid] )
            low = mid + 1;
        else
            return mid;
    }
    return -1;
}

/* binsearch2:find x in v[0] <= v[1] <= ... v[n-1] */

int binsearch2(int x, int v[], int n) 
{
    int low, mid, high;
    
    low = 0;
    high = n - 1;
    mid = (low+high) / 2;	
    while (( low < high ) &&(x != v[mid]))
	{
        if ( x < v[mid] )
            high = mid - 1;
        else
            low = mid + 1;
        mid = (low+high) / 2;		
    }
    if ( x == v[mid] )
        return mid;
    else
        return -1;
}
 
图1.

      E x c e r c i s e 3 − 2 Excercise\quad 3-2 Excercise32:输出结果如图2所示

#include <stdio.h>

void escape(char s[], char t[]);  
void unescape(char s[], char t[]); 
int main(void) 
{
    char text1[100] = "\aHello,\n\tWorld! Mistakee\b was \"Extra 'e'\"!\n";
    char text2[100];
    char text3[100];    
    printf("Original string:\n%s\n", text1);
    
    escape(text2, text1);
    printf("Escaped string:\n%s\n", text2);
    
    unescape(text2, text3);
    printf("Unescaped string:\n%s\n", text3);
    
    return 0;
}


/*  Copies string t to string s, converting special
    characters into their appropriate escape sequences.
    The "complete set of escape sequences" found in
    K&R Chapter 2 is used, with the exception of:
    
    \? \' \ooo \xhh
    
    as these can be typed directly into the source code,
    (i.e. without using the escape sequences themselves)
    and translating them is therefore ambiguous.    */
void escape(char s[], char t[]) 
{
    int i=0;
    int j=0;
    while ( t[i]!='\0' ) 
	{
        switch (t[i])
		{
			case '\t':
			    s[j++]='\\';
			    s[j++]='t';			
			    break;
			case '\n':
			    s[j++]='\\';
			    s[j++]='n';				
			    break;	
			case '\a':
			    s[j++]='\\';
			    s[j++]='a';			
			    break;
			case '\b':
			    s[j++]='\\';
			    s[j++]='b';			
			    break;
			case '\f':
			    s[j++]='\\';
			    s[j++]='f';			
			    break;
			case '\r':
			    s[j++]='\\';
			    s[j++]='r';			
			    break;
			case '\v':
			    s[j++]='\\';
			    s[j++]='v';			
			    break;	
			case '\"':
			    s[j++]='\\';
			    s[j++]='\"';			
			    break;
			case '\\':
			    s[j++]='\\';
			    s[j++]='\\';			
			    break;								
			default:
			    s[j++]=t[i];			
			    break;			
		}
		i++;
    }
	s[j]='\0';
}

/*  Copies string s to string t, converting escape sequences
    into their appropriate special characters. See the comment
    for escape() for remarks regarding which escape sequences
    are translated. */
void unescape(char s[], char t[]) 
{
    int i=0;
    int j=0;
    while ( s[i]!='\0' ) 
	{
        switch (s[i])
		{
			case '\\':
                switch (s[++i])
		        {
		        	case 't':
		        	    t[j++]='\t';		
		        	    break;
		        	case 'n':
		        	    t[j++]='\n';			
		        	    break;	
		        	case 'a':
		        	    t[j++]='\a';		
		        	    break;
		        	case 'b':
		        	    t[j++]='\b';		
		        	    break;
		        	case 'f':
		        	    t[j++]='\f';		
		        	    break;
		        	case 'r':
		        	    t[j++]='\r';		
		        	    break;
		        	case 'v':
		        	    t[j++]='\v';		
		        	    break;
		        	case '\"':
		        	    t[j++]='\"';			
		        	    break;
		        	case '\\':
		        	    t[j++]='\\';		
		        	    break;
                    default:
                
                /*  We don't translate this escape
                    sequence, so just copy it verbatim  */                
                        t[j++] = '\\';
                        t[j++] = t[i];						
		        }			
			    break;								
			default:
			    t[j++]=s[i];			
			    break;			
		}
		++i;
    }
	t[j]='\0';
}
 
图2.

      E x c e r c i s e 3 − 3 Excercise\quad 3-3 Excercise33:输出结果如图3所示。

#include <stdio.h>

#define MAXIMUM 1000

void expand(char s1[], char s2[]);
int is_valid(char c);

int main()
{
    char s1[MAXIMUM] = "-A-C-E-I first a-z0-9 second -a-z third   9-2 fourth   6-6- end-";	
    char s2[MAXIMUM];
    printf("%s\n", s1);
    expand(s1, s2);
    printf("%s\n", s2);
    return 0;
}

void expand(char s1[], char s2[]) 
{
    char c, d;
    int i, j;
    i = j = 0;

    while ('\0' != (c = s1[i++])) 
	{
        if (is_valid(c) && '-' == s1[i]  && is_valid(s1[i + 1])) 
		{
            i++;
            d = s1[i];
            if (c > d) 
			{
                while (c > d) 
				{
                    s2[j++] = c--;
                }
            }
            else 
			{
                while (c < d) 
				{
                    s2[j++] = c++;
                }
            }
        }
        else 
		{
            s2[j++] = c;
        }
    }
    s2[j] = '\0';
}

int is_valid(char c)
{
    if(((c>='a') && (c<='z'))	|| ((c>='A') && (c<='Z'))	|| ((c>='0') && (c<='9')))
	{
		return 1;
	}
	else
	{
		return 0;
	}	
}
 
图3.

      E x c e r c i s e 3 − 4 Excercise\quad 3-4 Excercise34:下面我们首先来看一段代码以及输出,输出结果如图4所示。这里 i n t int int型变量能表示的数的最大范围是 [ − 2147483648 , 2147483647 ] [-2147483648,2147483647] [2147483648,2147483647],这里我们可以看到 i n t int int型可以表示的最大负数的绝对值要比 i n t int int型可以表示的最大正数的值大一(其它类型的有符号数的类型也是一样的),当我们在尝试使用书中的那个版本的 i t o a itoa itoa接口来将 i n t int int型可以表示的最大负数 − 2147483648 -2147483648 2147483648转换为字符串的时候会出现问题。书中的那个版本的 i t o a itoa itoa接口会首先将要转换的负数变成正数,但是对于 i n t int int型,它可以表示的最大正数是 2147483647 2147483647 2147483647,因此从图4中我们可以看到 i n t u = − i ; int u=-i; intu=i;操作之后 u u u的值还是 − 2147483648 -2147483648 2147483648,因此书中的那个版本的 i t o a itoa itoa接口中的 d o w h i l e do\quad while dowhile循环只会运行一次且就算是这一次对个位数的转换也是错误的,这是因为这一次循环中 n % 10 n\%10 n%10操作的结果是 − 8 -8 8,因此 n % 10 + ′ 0 ′ n\%10+'0' n%10+0操作的结果是 40 40 40(字符 ′ 0 ′ '0' 0 A S C I I ASCII ASCII码值是48,字符 ′ ( ′ '(' ( A S C I I ASCII ASCII码值是40,),因此这里并没有得到我们所预期的字符 ′ 8 ′ '8' 8。为了能够成功实现对 i n t int int型可以表示的最大负数的转换,改进后的程序在判断 d o w h i l e do\quad while dowhile循环的执行的时候改为 w h i l e ( n / = 10 ) ; while ( n /= 10 ); while(n/=10);,而不是 w h i l e ( ( n / = 10 ) > 0 ) ; while( ( n /= 10 )>0); while((n/=10)>0);也就是不为0就可以继续执行循环,且改进后的程序在求余数之后做了绝对值的操作。

#include <stdio.h>
#include <limits.h>


int main(void)
{
	char c='\0';
	printf("sizeof(int)=%d\n",sizeof(int));
    printf("Signed int[%d to %d]\n", INT_MIN, INT_MAX);
    printf("Unsigned int[0 to %u]\n", UINT_MAX);
    int i=-2147483648;
    int u=-i;	
	printf("i=%d\n",i);	
	printf("u=%d\n",u);			
	c=(u%10)+'0';
	printf("c=%d\n",c);	
	printf("c=%c\n",c);		
	return 0;
}
 
图4.
#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[]);
void reverse(char s[]);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer);
    printf("Buffer : %s\n", buffer);
    
    return 0;
}

void itoa_myself(int n, char s[]) 
{
    int i, sign;
    sign = n;
    
    i = 0;
    do 
	{
        s[i++] = abs(n % 10) + '0';
    } while ( n /= 10 );
    if (sign < 0)
        s[i++] = '-';
    
    s[i] = '\0';
    reverse(s);
}

void reverse(char s[]) 
{
    int c, i, j;
    for ( i = 0, j = strlen(s)-1; i < j; i++, j--) 
	{
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

      E x c e r c i s e 3 − 5 Excercise\quad 3-5 Excercise35

#include<stdio.h>
#include<string.h>
#include<stdlib.h>

void itob(int n , char s[], int b);
void reverse(char s[]);

#define MAXIMUM 100

int main(){
    int b = 16;
    char s[MAXIMUM];
    itob(-2147483648,s,b);
    printf("Base %d = %s\n",b,s);
    return 0;
}

void itob(int n, char s[], int b)
{
    int i = 0;
	int negative=0;
	if(n<0)
	{
		negative=-1;			
	}
    if((b!=2) && (b!=8) && (b!=16)) 
	{		
	    printf("base error\n");	
	}		
    do
    {
        if (abs(n%b)>9)
            s[i++]= abs(n%b) +'A'-10;
        else
            s[i++] = abs(n%b) +'0';
    } while ((n/=b));
	if(negative==-1)
	{
		s[i++]='-';			
	}
    s[i] = '\0';	
    reverse(s);
}

void reverse (char s[])
{
    int i , j , c;
    for (i = 0, j = strlen(s)-1; i < j; i++,j--)
    c = s[i], s[i]=s[j], s[j]=c;
}

      E x c e r c i s e 3 − 6 Excercise\quad 3-6 Excercise36

#include <stdlib.h>
#include <stdio.h>
#include <limits.h>
#include <string.h>

void itoa_myself(int n, char s[], int minmum);
void reverse(char s[]);

int main(void) 
{
    char buffer[100];
    
    printf("INT_MIN: %d\n", INT_MIN);
    itoa_myself(INT_MIN, buffer,25);
    printf("Buffer : %s\n", buffer);
    
    return 0;
}

void itoa_myself(int n, char s[], int minmum) 
{
    int i, sign;
    sign = n;
    
    i = 0;
    do 
	{
        s[i++] = abs(n % 10) + '0';
    } while ( n /= 10 );
    if (sign < 0)
        s[i++] = '-';
	while(i<minmum)
	{
        s[i++] = ' ';		
	}	
    s[i] = '\0';
    reverse(s);
}

void reverse(char s[]) 
{
    int c, i, j;
    for ( i = 0, j = strlen(s)-1; i < j; i++, j--) 
	{
        c = s[i];
        s[i] = s[j];
        s[j] = c;
    }
}

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1585119.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

curl: (60) Peer‘s Certificate issuer is not recognized curl请求报错

此种情况多发生在自签名的证书或者证书和域名不对&#xff0c;报错含义是签发证书机构未经认证&#xff0c;无法识别。解决办法就是替换证书&#xff08;补充证书机构&#xff09;文件就好&#xff0c;如果没有可用的证书可以去Gworg申请一个。

记录我第一场面了40min+的面试

中冶赛迪信息技术(重庆)有限公司 国企 首先3/24投递的&#xff0c;4/10打了电话问是否接受劳务派遣&#xff0c;我当时不知道劳务派遣什么意思&#xff0c;问了和售前售后是不是类似&#xff0c;得到了不大一样的回答&#xff0c;后面加了微信&#xff0c;定了11开始面试。 这…

【计算机考研】数据结构都不会,没有思路,怎么办?

基础阶段&#xff0c;并不需要过于专门地练习算法。重点应该放在对各种数据结构原理的深入理解上&#xff0c;也可以说先学会做选择题、应用题。 因为在考试中&#xff0c;大部分的算法题目&#xff0c;尤其是大题&#xff0c;往往可以通过简单的暴力解决方案得到较高的分数。…

【Java8新特性】四、强大的Stream api

​ 这里写自定义目录标题 一、了解Stream二、流(stream)到底是什么&#xff1f;三、Stream操作的三个步骤四、创建Stream的四种方式五、Stream 的中间操作1、筛选和切片2、map 映射3、排序 六、Stream 的终止操作1、查找和匹配2、归约3、收集 一、了解Stream Stream是Java8中…

【Locust分布式压力测试】

Locust分布式压力测试 https://docs.locust.io/en/stable/running-distributed.html Distributed load generation A single process running Locust can simulate a reasonably high throughput. For a simple test plan and small payloads it can make more than a thousan…

08 - 镜像管理之:镜像仓库harbor介绍

本文参考&#xff1a;原文1 1 Harbor仓库介绍 Docker容器应用的开发和运行离不开可靠的镜像管理&#xff0c;虽然Docker官方也提供了公共的镜像仓库&#xff0c;但是从安全和效率等方面考虑&#xff0c;部署我们私有环境内的Registry 也是非常必要的。 之前介绍了Docker私有仓…

CSS - 你实现过宽高自适应的正方形吗

难度 难度级别:中高级及以上 提问概率:80% 宽高自适应的需求并不少见,尤其是在当今流行的大屏系统开发中更是随处可见,很显然已经超越了我们日常将div写死100px这样的范畴,那么如何实现一个宽高自适应的正方形呢?这里提出两种实现方案。…

pygame旋转角度发射射线

self.x self.x math.cos(math.radians(self.xuanzhuanjiao)) * 70 self.y self.y - math.sin(math.radians(self.xuanzhuanjiao)) * 70 旋转角度&#xff0c;70是间隔 间隔太小会卡 import pygame from pygame.locals import * import sys import mathpygame.init()width, …

SpringCloudAlibaba-整合sleuth和zipkin(六)

目录地址&#xff1a; SpringCloudAlibaba整合-CSDN博客 一、整合sleuth 1.引入依赖 在需要追踪的微服务中引入依赖&#xff0c;user、order、product <dependency><groupId>org.springframework.cloud</groupId><artifactId>spring-cloud-starter…

摩尔信使MThings之数据网关:Modbus转MQTT

由于现场设备和物联网云平台采用了不同的通信协议&#xff0c;而为了实现它们之间的互操作性和数据交换&#xff0c;需要进行协议转换。 MQTT作为一种轻量级的、基于发布/订阅模式的通信协议&#xff0c;适用于连接分布式设备和传感器网络&#xff0c;而MODBUS协议则常用于工业…

位图布隆过滤器的原理及实现

目录 位图的概念&#xff1a; 位图的前置知识&#xff1a;位运算 位图的实现&#xff1a; 位图的基本参数和构造方法&#xff1a; 位图的插入&#xff1a; 位图的查找&#xff1a; 位图的删除&#xff1a; 布隆过滤器概念&#xff1a; 布隆过滤器的实现&#xff1a; …

ThinkPHP审计(1) 不安全的SQL注入PHP反序列化链子phar利用简单的CMS审计实例

ThinkPHP代码审计(1) 不安全的SQL注入&PHP反序列化链子phar利用&简单的CMS审计实例 文章目录 ThinkPHP代码审计(1) 不安全的SQL注入&PHP反序列化链子phar利用&简单的CMS审计实例一.Thinkphp5不安全的SQL写法二.Thinkphp3 SQL注入三.Thinkphp链5.1.x结合phar实现…

基于springboot+vue+Mysql的线上教学平台

开发语言&#xff1a;Java框架&#xff1a;springbootJDK版本&#xff1a;JDK1.8服务器&#xff1a;tomcat7数据库&#xff1a;mysql 5.7&#xff08;一定要5.7版本&#xff09;数据库工具&#xff1a;Navicat11开发软件&#xff1a;eclipse/myeclipse/ideaMaven包&#xff1a;…

【C++题解】1329. 求梯形的面积

问题&#xff1a;1329. 求梯形的面积 类型&#xff1a;基本运算、小数运算 题目描述&#xff1a; 梯形面积的求解公式为S(ab)h/2 。从键盘读入一个梯形的上底 a、下底 b 和高 h &#xff0c;请计算表梯形的面积。&#xff08;结果保留1位小数&#xff09;。&#xff08;5.1.1…

企业加密软件好用的有哪些?电脑文件安全守护不容错过

近年来泄密问题频发&#xff0c;重要数据外泄造成公司损失&#xff0c;越来越多的企业开始使用防泄密软件&#xff0c;来保护公司内部数据安全&#xff0c;防止信息泄露的问题出现&#xff0c;维护公司权益。那么&#xff0c;既然要使用防泄密软件&#xff0c;必然是要安装有用…

unity数组

数组的定义 动态初始化:在定义数组时只指定数组的长度&#xff0c;由系统自动为元素赋初值的方式。 静态初始化:定义数组的同时就为数组的每个元素赋值 数组的静态初始化有两种方式 1、类型门数组名new 类型[]{元素&#xff0c;元素&#xff0c;…}; 2、类型[数组名{元素&am…

股票高胜率的交易法则是什么?

股票交易中的高胜率交易法则并非一成不变&#xff0c;而是根据市场状况、个人投资风格和经验等多种因素综合而定的。以下是一些有助于提升交易胜率的法则和策略&#xff1a; 1.趋势跟踪法则&#xff1a;在股票交易中&#xff0c;趋势跟踪是一种有效的策略。通过观察大盘和个股…

前端学习<四>JavaScript基础——16-内置对象:Number和Math

内置对象 Number 的常见方法 Number.isInteger() 判断是否为整数 语法&#xff1a; 布尔值 Number.isInteger(数字); toFixed() 小数点后面保留多少位 语法&#xff1a; 字符串 myNum.toFixed(num); 解释&#xff1a;将数字 myNum 的小数点后面保留 num 位小数&#xff…

Redis从入门到精通(九)Redis实战(六)基于Redis队列实现异步秒杀下单

↑↑↑请在文章开头处下载测试项目源代码↑↑↑ 文章目录 前言4.5 分布式锁-Redisson4.5.4 Redission锁重试4.5.5 WatchDog机制4.5.5 MutiLock原理 4.6 秒杀优化4.6.1 优化方案4.6.2 完成秒杀优化 4.7 Redis消息队列4.7.1 基于List实现消息队列4.7.2 基于PubSub的消息队列4.7.…

中国独立开发者项目列表

1. 为什么有这个表 作为开发者其实比较好奇其他人在做什么业余项目(不管目的是做到盈利/玩票/试试看) 所以特意建了这个库。欢迎各位开发者把自己的项目加进来~ 发 Pull Request 或 Issue 即可 (入选标准:必须是网站或App,不能是开发者工具或论坛型网站) 地址:GitHub - …