C Primer Plus第十二章编程练习答案

学完C语言之后,我就去阅读《C Primer Plus》这本经典的C语言书籍,对每一章的编程练习题都做了相关的解答,仅仅代表着我个人的解答思路,如有错误,请各位大佬帮忙点出!

1.不使用全局变量,重写程序清单12.4。

#include <stdio.h>
void critic(int* units)
{
    printf("No luck, my friend. Try again.\n");
    scanf("%d", units);
}
int main(void)
{
    int units;

    printf("How many pounds to a firkin of butter?\n");
    scanf("%d", &units);

    while (units != 56)
    {
        critic(&units);
    }
    printf("You must have looked it up!\n");

    return 0;
}

2.在美国,通常以英里/加仑来计算油耗;在欧洲,以升/100 公里来计 算。下面是程序的一部分,提示用户选择计算模式(美制或公制),然后接 收数据并计算油耗。

// pe12-2b.c

// 与 pe12-2a.c 一起编译

#include <stdio.h>

#include "pe12-2a.h"

int main(void)

{

int mode;

printf("Enter 0 for metric mode, 1 for US mode: ");

scanf("%d", &mode);

while (mode >= 0)

{ set_mode(mode);

get_info(); show_info();

printf("Enter 0 for metric mode, 1 for US mode");

printf(" (-1 to quit): "); scanf("%d", &mode); }

printf("Done.\n"); return 0; }

下面是是一些输出示例:

Enter 0 for metric mode, 1 for US mode: 0

Enter distance traveled in kilometers: 600

Enter fuel consumed in liters: 78.8

Fuel consumption is 13.13 liters per 100 km.

Enter 0 for metric mode, 1 for US mode (-1 to quit): 1

Enter distance traveled in miles: 434

Enter fuel consumed in gallons: 12.7

Fuel consumption is 34.2 miles per gallon.

Enter 0 for metric mode, 1 for US mode (-1 to quit): 3

Invalid mode specified. Mode 1(US) used.

Enter distance traveled in miles: 388

Enter fuel consumed in gallons: 15.3

Fuel consumption is 25.4 miles per gallon.

Enter 0 for metric mode, 1 for US mode (-1 to quit): -1

Done.

如果用户输入了不正确的模式,程序向用户给出提示消息并使用上一次 输入的正确模式。请提供pe12-2a.h头文件和pe12-2a.c源文件。源代码文件应 定义3个具有文件作用域、内部链接的变量。一个表示模式、一个表示距 离、一个表示消耗的燃料。get_info()函数根据用户输入的模式提示用户输入 相应数据,并将其储存到文件作用域变量中。show_info()函数根据设置的模 式计算并显示油耗。可以假设用户输入的都是数值数据。

#include <stdio.h>
#include "pe12-2a.h"
int main(void)
{
    int mode;

    printf("Enter 0 for metric mode, 1 for US mode: ");
    scanf("%d", &mode);
    while (mode >= 0)
    {
        set_mode(mode);
        get_info();
        show_info();
        printf("Enter 0 for metric mode, 1 for US mode");
        printf(" (-1 to quit): ");
        scanf("%d", &mode);
    }
    printf("Done.\n");

    return 0;
}

3.重新设计编程练习2,要求只使用自动变量。该程序提供的用户界面 不变,即提示用户输入模式等。但是,函数调用要作相应变化。

#include <stdio.h>
#include "pe12-2a.h"
int main(void)
{
    int temp, mode;
    double range, fuel;

    printf("Enter 0 for metric mode, 1 for US mode: ");
    scanf("%d", &mode);
    temp = mode;
    while (mode >= 0)
    {
        set_mode(&mode, &temp);
        get_info(temp, &range, &fuel);
        show_info(temp, range, fuel);
        printf("Enter 0 for metric mode, 1 for US mode");
        printf(" (-1 to quit): ");
        scanf("%d", &mode);
    }
    printf("Done.\n");

    return 0;
}

4.在一个循环中编写并测试一个函数,该函数返回它被调用的次数。

#include <stdio.h>
static int count = 0;
int counter(void)
{
    return ++count;
}
int main(void)
{
    int i, j;
    printf("Please enter a integer: ");
    scanf("%d", &i);

    for (j = 1; j <= i; j++)
    {
        printf("count = %d\n", counter());
    }
    printf("The function called %d times.\n", count);

    return 0;
}

5.编写一个程序,生成100个1~10范围内的随机数,并以降序排列(可 以把第11章的排序算法稍加改动,便可用于整数排序,这里仅对整数排 序)。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
#define LEN 100
void sort(int a[], int n)
{
    int i, j, t;

    for (i = 0; i < n - 1; i++)
    {
        for (j = i + 1; j < n; j++)
        {
            if (a[i] < a[j])
            {
                t = a[j];
                a[j] = a[i];
                a[i] = t;
            }
        }
    }
    return;
}
void show_array(const int a[], int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        printf("%-3d ", a[i]);
        if (0 == (i + 1) % 10)
        {
            printf("\n");
        }
    }
    printf("\n");
}
int main(void)
{
    int i, a[LEN];

    srand((unsigned int)time(0));
    for (i = 0; i < LEN; i++)
    {
        a[i] = rand() % 10 + 1;
    }
    printf("Array:\n");
    show_array(a, LEN);
    sort(a, LEN);
    printf("After sorting:\n");
    show_array(a, LEN);

    return 0;
}

6.编写一个程序,生成1000个1~10范围内的随机数。不用保存或打印 这些数字,仅打印每个数出现的次数。用 10 个不同的种子值运行,生成的 数字出现的次数是否相同?可以使用本章自定义的函数或ANSI C的rand()和 srand()函数,它们的格式相同。这是一个测试特定随机数生成器随机性的方 法。

#include <stdio.h>
#include <stdlib.h>
#define N 10
#define LEN 1000
int main(void)
{
    int i, temp, a[N + 1];
    unsigned int seeds;

    for (seeds = 1; seeds <= N; seeds++)
    {
        printf("Time #%d:\n", seeds);
        srand(seeds);
        for (i = 0; i < N + 1; i++)
        {
            a[i] = 0;
        }
        for (i = 0; i < LEN; i++)
        {
            temp = rand() % 10 + 1;
            a[temp]++;
        }
        for (i = 1; i < N + 1; i++)
        {
            printf("%-3d appeared %d times.\n", i, a[i]);
        }
        printf("Total random numbers: %d\n\n", LEN);
    }

    return 0;
}

 7.编写一个程序,按照程序清单12.13输出示例后面讨论的内容,修改该 程序。使其输出类似: Enter the number of sets;

enter q to stop : 18

How many sides and how many dice? 6 3

Here are 18 sets of 3 6-sided throws.

12 10 6 9 8 14 8 15 9 14 12 17 11 7 10

13 8 14 H

ow many sets?

Enter q to stop: q

#include <stdio.h>
#include <time.h>
#include <stdlib.h>
int rollem(int sides)
{
    return rand() % sides + 1;
}
int main(void)
{
    int dice, count, roll;
    int sides;
    int set, sets;

    srand((unsigned int)time(0));
    printf("Enter the number of sets.\nEnter q to stop: ");
    while (scanf("%d", &sets) == 1)
    {
        printf("How many sides and how many dice?\n");
        printf("Please two integers: ");
        if (scanf("%d %d", &sides, &dice) != 2)
        {
            puts("Not integers -- terminating input loop.");
            break;
        }
        printf("Here are %d sets of %d %d-sided throws.\n", sets, dice, sides);
        for (set = 0; set < sets; set++)
        {
            for (roll = 0, count = 0; count < dice; count++)
            {
                roll += rollem(sides);
            }
            printf("%-3d", roll);
            if (0 == (set + 1) % 8)
            {
                putchar('\n');
            }
        }
        printf("\nHow many sets? Enter q to stop: ");
    }
    puts("GOOD FORTUNE TO YOU!\n");

    return 0;
}

8.下面是程序的一部分:

// pe12-8.c

#include <stdio.h>

int * make_array(int elem, int val);

void show_array(const int ar [], int n);

int main(void)

{ int * pa;

int size;

int value;

printf("Enter the number of elements: ");

while (scanf("%d", &size) == 1 && size > 0)

{ printf("Enter the initialization value: ");

scanf("%d", &value);

pa = make_array(size, value);

if (pa) { show_array(pa, size); free(pa); }

printf("Enter the number of elements (<1 to quit): "); }

printf("Done.\n");

return 0; }

提供make_array()和show_array()函数的定义,完成该程序。make_array() 函数接受两个参数,第1个参数是int类型数组的元素个数,第2个参数是要赋 给每个元素的值。该函数调用malloc()创建一个大小合适的数组,将其每个 元素设置为指定的值,并返回一个指向该数组的指针。show_array()函数显 示数组的内容,一行显示8个数。

#include <stdio.h>
#include <stdlib.h>
int* make_array(int elem, int val)
{
    int i;
    int* pt;
    pt = (int*)malloc(elem * sizeof(int));
    if (NULL == pt)
    {
        printf("Memory allocation failed!\n");
        exit(0);
    }
    printf("Output %d numbers:\n", val);
    for (i = 0; i < elem; i++)
    {
        pt[i] = val;
    }
    return pt;
}
void show_array(const int ar[], int n)
{
    int i;

    for (i = 0; i < n; i++)
    {
        printf("%d ", ar[i]);
        if (0 == (i + 1) % 8)
        {
            printf("\n");
        }
    }
    printf("\n");
    return;
}
int main(void)
{
    int* pa;
    int size;
    int value;

    printf("Enter the number of elements: ");
    while (scanf("%d", &size) == 1 && size > 0)
    {
        printf("Enter the initialization value: ");
        scanf("%d", &value);
        pa = make_array(size, value);
        if (pa)
        {
            show_array(pa, size);
            free(pa);
        }
        printf("Enter the number of elements (<1 to quit): ");
    }
    printf("Done.\n");

    return 0;
}

9.编写一个符合以下描述的函数。首先,询问用户需要输入多少个单 词。然后,接收用户输入的单词,并显示出来,使用malloc()并回答第1个问 题(即要输入多少个单词),创建一个动态数组,该数组内含相应的指向 char的指针(注意,由于数组的每个元素都是指向char的指针,所以用于储 存malloc()返回值的指针应该是一个指向指针的指针,且它所指向的指针指向char)。在读取字符串时,该程序应该把单词读入一个临时的char数组, 使用malloc()分配足够的存储空间来储存单词,并把地址存入该指针数组 (该数组中每个元素都是指向 char 的指针)。然后,从临时数组中把单词 拷贝到动态分配的存储空间中。因此,有一个字符指针数组,每个指针都指 向一个对象,该对象的大小正好能容纳被储存的特定单词。下面是该程序的 一个运行示例:

How many words do you wish to enter? 5

Enter 5 words now:

I enjoyed doing this exerise

Here are your words: I

enjoyed

doing

this

exercise

#include <stdio.h>
#include <string.h>
#include <stdlib.h>
#define LEN 256
int main(void)
{
    char** pt;
    int i, n, length;
    static char temp[LEN];

    printf("How many words do you wish to enter? ");
    scanf("%d", &n);
    if ((pt = (char**)malloc(n * sizeof(char*))) != NULL)
    {
        printf("Enter %d words now:\n", n);
        for (i = 0; i < n; i++)
        {
            scanf("%255s", temp);
            length = strlen(temp) + 1;
            pt[i] = (char*)malloc(length * sizeof(char));
            if (NULL == pt[i])
            {
                printf("Memory allocation failed!\n");
                exit(EXIT_FAILURE);
            }
            strcpy(pt[i], temp);
        }
        printf("Here are your words:\n");
        for (i = 0; i < n; i++)
        {
            puts(pt[i]);
            free(pt[i]);
            pt[i] = NULL;
        }
        free(pt);
        pt = NULL;
    }
    else
    {
        printf("Memory allocation failed!\n");
        exit(EXIT_FAILURE);
    }

    return 0;
}

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

如若内容造成侵权/违法违规/事实不符,请联系我们进行投诉反馈qq邮箱809451989@qq.com,一经查实,立即删除!

相关文章

idea使用Alibaba Cloud Toolkit插件远程操作Docker

idea使用Alibaba Cloud Toolkit插件远程操作Docker 文章目录 前言一、tcp://IP:2375或者Unix socket 连接Docker(不安全)问题1&#xff1a;为什么本地虚拟机能连上&#xff0c;xxx云ECS服务器连不上&#xff1f;问题2&#xff1a;什么是Unix域套接字&#xff1f;有什么作用&…

Linux之创建进程、查看进程、进程的状态以及进程的优先级

文章目录 前言一、初识fork1.演示2.介绍3.将子进程与父进程执行的任务分离4.多进程并行 二、进程的状态1.进程的状态都有哪些&#xff1f;2.查看进程的状态2.运行&#xff08;R&#xff09;3.阻塞4.僵尸进程&#xff08;Z&#xff09;1.僵尸状态概念2.为什么要有僵尸状态&#…

伺服系统使用S曲线

在之前文章《S形曲线规划方式汇总》 介绍过贝塞尔曲线方式&#xff0c;并且在Marlin开源工程中也有贝塞尔曲线步进系统的实现方式。本篇介绍伺服系统中基于时间分割法实现的贝塞尔S曲线。 1 贝塞尔曲线路程规划 上文中推导过贝塞尔曲线&#xff0c;本文直接用结论&#xff1a…

OFGF光流引导特征:用于视频动作识别的快速且稳健的运动表示【含源码】

论文地址:https://openaccess.thecvf.com/content_cvpr_2018/papers/Sun_Optical_Flow_Guided_CVPR_2018_paper.pdf 这个 repo 包含论文的实现代码: Optical Flow Guided Feature: A Fast and Robust Motion Representation for Video Action Recognition,Shuyang Sun,Zh…

TCO-PEG-Thiol,反式环辛烯聚乙二醇巯基,具有末端硫醇基团的双功能TCO PEG衍生物

产品描述&#xff1a; TCO PEG Thiol是具有末端硫醇基团的双功能TCO PEG衍生物。TCO&#xff08;反式环辛烯&#xff09;基团与四嗪基团快速有效地反应&#xff0c;而硫醇&#xff08;巯基&#xff09;可用于与马来酰亚胺反应&#xff0c;与金表面结合并参与许多其他反应。 TC…

医疗IT系统安科瑞隔离电源装置在医院的应用

【摘要】介绍该三级综合医院采用安科瑞隔离电源系统5件套&#xff0c;使用落地式配电柜安装方式&#xff0c;从而实现将TN系统转化为IT系统&#xff0c;以及系统绝缘情况监测。 【关键词】医用隔离电源系统&#xff1b;IT系统&#xff1b;绝缘情况监测&#xff1b;三级综合医院…

Java版本企业电子招投标采购系统源码之项目说明和开发类型源码

项目说明 随着公司的快速发展&#xff0c;企业人员和经营规模不断壮大&#xff0c;公司对内部招采管理的提升提出了更高的要求。在企业里建立一个公平、公开、公正的采购环境&#xff0c;最大限度控制采购成本至关重要。符合国家电子招投标法律法规及相关规范&#xff0c;以及…

办公OA系统性能分析案例

前言 信息中心老师反应&#xff0c;用户反馈办公系统有访问慢的情况&#xff0c;需要通过流量分析系统来了解系统的运行情况&#xff0c;此报告专门针对系统的性能数据做了分析。 信息中心已部署NetInside流量分析系统&#xff0c;使用流量分析系统提供实时和历史原始流量&am…

基于LeNet-5的手写数字识别实战

图像识别是计算机视觉最常用的任务之一&#xff0c;几乎所有的有关图像识别的教程都会将MNIST数据集作为入门数据集&#xff0c;因为MNIST数据集是图像识别问题中难度最小、特征差异较为明显的数据集&#xff0c;非常适合作为图像识别入门者的学习案例。本案例使用MNIST数据集&…

【k8s】【Prometheus】【待写】

环境 k8s v1.18.0 192.168.79.31 master 192.168.79.32 node-1 192.168.79.33 node-2一、Prometheus 对 kubernetes 的监控 1.1 node-exporter 组件安装和配置 node-exporter 可以采集机器&#xff08;物理机、虚拟机、云主机等&#xff09;的监控指标数据&#xff0c;能够采…

微服务开发系列 第七篇:RocketMQ

总概 A、技术栈 开发语言&#xff1a;Java 1.8数据库&#xff1a;MySQL、Redis、MongoDB、Elasticsearch微服务框架&#xff1a;Spring Cloud Alibaba微服务网关&#xff1a;Spring Cloud Gateway服务注册和配置中心&#xff1a;Nacos分布式事务&#xff1a;Seata链路追踪框架…

网络通信:http协议

虽然我们说, 应用层协议是我们程序猿自己定的. 但实际上, 已经有大佬们定义了一些现成的, 又非常好用的应用层协议, 供我们直接参考使用. HTTP(超文本传输协议) 就是其中之一. 认识URL 统一资源定位符(Uniform Resource Locator&#xff0c;缩写&#xff1a;URL)&#xff0c;…

DAY07_HTMLCSS

目录 1 HTML1.1 介绍1.1.1 WebStrom中基本配置 1.2 快速入门1.3 基础标签1.3.1 标题标签1.3.2 hr标签1.3.3 字体标签1.3.4 换行标签1.3.5 段落标签1.3.6 加粗、斜体、下划线标签1.3.7 居中标签1.3.8 案例 1.4 图片、音频、视频标签1.5 超链接标签1.6 列表标签1.6.1 列表中图表类…

【Selenium】提高测试爬虫效率:Selenium与多线程的完美结合

前言 使用Selenium 创建多个浏览器&#xff0c;这在自动化操作中非常常见。 而在Python中&#xff0c;使用 Selenium threading 或 Selenium ThreadPoolExecutor 都是很好的实现方法。 应用场景&#xff1a; 创建多个浏览器用于测试或者数据采集&#xff1b;使用Selenium…

C语言深度解析--操作符

目录 操作符 1.算数操作符 2.移位操作符 左移操作符<<&#xff1a; 右移操作符>>&#xff1a; 3.位操作符 按位与&&#xff1a; 按位或 | &#xff1a; 按位异或 ^ &#xff1a; 4.赋值操作符 5.单目操作符 6.关系操作符 7.逻辑操作符 8.条件操作…

如何快速搭建SpringBoot+Vue前后端分离的开发环境

唠嗑部分 今天我们来说一说&#xff0c;如何快速搭建SpringBootVue前后端分离的开发环境 需要前置环境nodejs&#xff0c;请自行安装(傻瓜式安装) SpringBoot采用2.4.2版本&#xff0c;Vue采用Vue2版本 言归正传 创建Vue项目 1、安装vue npm install -g vue/cli2、检查v…

TDengine 报错 failed to connect to server, reason: Unable to establish connection

一、前文 TDengine 入门教程——导读 二、遇到问题 taos 命令行&#xff08;CLI&#xff09;连接不上&#xff0c;进不去。 [rootiZ2ze30dygwd6yh7gu6lskZ ~]# taos Welcome to the TDengine Command Line Interface, Client Version:3.0.0.1 Copyright (c) 2022 by TDengine…

Linux 安装nodejs、npm、yarn、nrm(超实用)

前言&#xff1a;初衷想要本地通过dockerfile文件直接把项目打包到linux服务器&#xff0c;不用再本地加载再上传等&#xff0c;后续再贴上配置文件 一、什么是nodejs 来自官网的介绍&#xff0c;Node.js 是一个开源的跨平台 JavaScript 运行时环境。它几乎是任何类型项目的流…

JVM内存结构介绍

我们都知道&#xff0c;Java代码是要运行在虚拟机上的&#xff0c;而虚拟机在执行Java程序的过程中会把所管理的内存划分为若干个不同的数据区域&#xff0c;这些区域都有各自的用途。其中有些区域随着虚拟机进程的启动而存在&#xff0c;而有些区域则依赖用户线程的启动和结束…

远程访问群晖Drive并挂载为电脑磁盘同步备份文件「无需公网IP」

文章目录 前言视频教程1.群晖Synology Drive套件的安装1.1 安装Synology Drive套件1.2 设置Synology Drive套件1.3 局域网内电脑测试和使用 2.使用cpolar远程访问内网Synology Drive2.1 Cpolar云端设置2.2 Cpolar本地设置2.3 测试和使用 3. 结语 转发自CSDN远程穿透的文章&…
最新文章