《C++ Primer Plus》(第6版)第8章编程练习

news2024/9/23 21:30:57

《C++ Primer Plus》(第6版)第8章编程练习

  • 《C++ Primer Plus》(第6版)第8章编程练习
    • 1. 打印字符串
    • 2. CandyBar
    • 3. 将string对象的内容转换为大写
    • 4. 设置并打印字符串
    • 5. max5()
    • 6. maxn()
    • 7. SumArray()

《C++ Primer Plus》(第6版)第8章编程练习

1. 打印字符串

编写通常接受一个参数(字符串的地址),并打印该字符串的函数。然而,如果提供了第二个参数(int类型),且该参数不为0,则该函数打印字符串的次数将为该函数被调用的次数(注意,字符串的打印次数不等于第二个参数的值而等于函数被调用的次数)。是的,这是一个非常可笑的函数,但它让您能够使用本章介绍的一些技术。在一个简单的程序中使用该函数,以演示该函数是如何工作的。

代码:

#include <iostream>
using namespace std;

const int strLen = 20;

void printStr(char *str, int n = 0);

int main()
{
    char str[strLen] = "bocchi the rock";
    printStr(str);
    cout << endl;
    printStr(str);
    cout << endl;
    printStr(str, 10);
    cout << endl;
    printStr(str, 30);
    cout << endl;

    system("pause");
    return 0;
}

void printStr(char *str, int n)
{
    static int count = 0;

    count++;
    while (n >= 0)
    {
        if (n == 0)
        {
            cout << str << endl;
            return;
        }
        else
        {
            for (int i = 0; i < count; i++)
            {
                cout << str << endl;
            }
            return;
        }
    }
}

运行结果:

在这里插入图片描述

2. CandyBar

CandyBar结构包含3个成员。第一个成员存储candy bar的品牌名称;第二个成员存储candy bar的重量(可能有小数);第三个成员存储candy bar的热量(整数)。 请编写一个程序,它使用一个这样的函数,即将CandyBar的引用、char指针、double和int作为参数,并用最后3个值设置相应的结构成员,最后3个参数的默认值分别为“Millennijum Munch "、2.85和350。另外,该程序还包含一个以 CandyBar 的引用为参数,并显示结构内容的函数。请尽可能使用const。

代码:

#include <iostream>
#include <cstring>
#include <string>
using namespace std;

const int strLen = 20;

typedef struct CandyBar
{
    char brand[strLen];
    double weight;
    int calories;
} CandyBar;

void fill_CandyBar(CandyBar &candyBar, const char brand[] = "Millennium Munch", const double weight = 2.85, const int calories = 350);
void display_CandyBar(const CandyBar &candyBar);

int main()
{
    CandyBar c1, c2;

    fill_CandyBar(c1);
    display_CandyBar(c1);
    cout << endl;
    fill_CandyBar(c2, "Margaret", 4.28, 900);
    display_CandyBar(c2);

    system("pause");
    return 0;
}

void fill_CandyBar(CandyBar &candyBar, const char brand[], const double weight, const int calories)
{
    strcpy_s(candyBar.brand, brand);
    candyBar.weight = weight;
    candyBar.calories = calories;
}

void display_CandyBar(const CandyBar &candyBar)
{
    cout << "Brand:" << candyBar.brand << endl;
    cout << "Weight:" << candyBar.weight << endl;
    cout << "Calories:" << candyBar.calories << endl;
}

运行结果:

在这里插入图片描述

3. 将string对象的内容转换为大写

编写一个函数,它接受一个指向string对象的引用作为参数“并将该string对象的内容转换为大写,为此可使用表6.4描述的函数 toupper()。然后编写一个程序,它通过使用一个循环让您能够用不同的输入来测试这个函数,该程序的运行情况如下:

Enter a string (q to quit) : go away
GO AWAY
Next string (q to quit) : good grief!
GOOD GRIEF!
Next string (q to quit): q
Bye.

代码:

#include <iostream>
#include <cstring>
#include <cctype>
using namespace std;

#define QUIT "q"

void strUpper(string &str);

int main()
{
    string s;

    cout << "Enter a string (q to quit): ";
    getline(cin, s);
    while (s != QUIT)
    {
        strUpper(s);
        cout << s << endl;
        cout << "Next string (q to quit): ";
        getline(cin, s);
    }
    cout << "Bye!\n";

    system("pause");
    return 0;
}

void strUpper(string &str)
{
    for (int i = 0; i < str.size(); i++)
    {
        str[i] = toupper(str[i]);
    }
}

运行结果:

在这里插入图片描述

4. 设置并打印字符串

下面是一个程序框架:

#include<iostream>

using namespace std;

#include<cstring>       //for strlen(),strcpy()

struct stringy {

char * str; //points to a string

int ct; //length of string (not couting '\0')

};

// prototypes for set(), show(), and show() go here

int main()
{
stringy beany;

char testing[]="Reality isn't what it used to be.";

set(beany,testing); //first argument is a reference,

//allocates space to hold copy of testing

//sets str member of beany to point to the

//new block, copies testing to new block,

//and sets ct member of beany

show(beany); //prints member string once

show(beany, 2); //prints member string twice

testing[0]= 'D';

testing[1] = 'u';

show(testing); //prints testing string once

show(testing, 3); //prints testing string thrice

show("Done!");

return 0;

}

请提供其中描述的函数和原型,从而完成该程序。注意,应有两个 show ()函数,每个都使用默认参数。请尽可能的使用 const 参数。 set() 使用 new 分配足够的空间来存储定指的字符串。这里使用的技术与设计和实现类使用的相似。(可能还必须修改头文件的名称,删除 using 编译指令,这取决于所用的编译器。)

代码:

#include <iostream>
using namespace std;

#include <cstring> //for strlen(),strcpy()

struct stringy
{
    char *str; // points to a string
    int ct;    // length of string (not counting '\0')
};

// prototypes for set(), show(), and show() go here
void set(stringy &beany, const char *testing);
void show(const stringy &sy, int times = 1);
void show(const char *str, int times = 1);

int main()
{
    stringy beany;
    char testing[] = "Reality isn't what it used to be.";

    set(beany, testing); // first argument is a reference,
    // allocates space to hold copy of testing
    // sets str member of beany to point to the
    // new block, copies testing to new block,
    // and sets ct member of beany
    show(beany);    // prints member string once
    show(beany, 2); // prints member string twice
    testing[0] = 'D';
    testing[1] = 'u';
    show(testing);    // prints testing string once
    show(testing, 3); // prints testing string thrice
    show("Done!");

    system("pause");
    return 0;
}

void set(stringy &beany, const char *testing)
{
    beany.ct = strlen(testing) + 1;
    beany.str = new char[beany.ct];
    strcpy_s(beany.str, beany.ct, testing);
}
void show(const stringy &sy, int times)
{
    for (int i = 0; i < times; i++)
        cout << sy.str << endl;
}
void show(const char *str, int times)
{
    for (int i = 0; i < times; i++)
        cout << str << endl;
}

运行结果:

在这里插入图片描述

5. max5()

编写模板函数 max5 (),它将一个包含 5 个 T 类型元素的数组作为参数,并返回数组中最大的元素(由于长度固定,因此可以在循环中使用硬编码,而不必通过参数来传递)。在一个程序中使用该函数,将 T 替换为一个包含 5 个 int 值的数组和一个包含 5 个 double 值的数组,以测试该函数。

代码:

#include <iostream>
using namespace std;

const int ArrSize = 5;

template <typename T>
T max5(T arr[])
{
    T t_max = arr[0];
    for (int i = 1; i < ArrSize; i++)
    {
        if (arr[i] > t_max)
            t_max = arr[i];
    }
    return t_max;
}

int main()
{
    int arr1[ArrSize] = {1, 6, 3, 2, 5};
    double arr2[ArrSize] = {1.20, 2.30, 5.2, 1.4, 2.7};

    cout << "The maximum value in int array is " << max5(arr1) << endl;
    cout << "The maximum value in double array is " << max5(arr2) << endl;

    system("pause");
    return 0;
}

运行结果:

在这里插入图片描述

6. maxn()

编写模板函数 maxn (),它将由一个 T 类型元素组成的数组和一个表示数组元素数目的整数作为参数,并返回数组中最大的元素。在程序对它进行测试,该程序使用一个包含 6 个 int 元素的数组和一个包含 4 个 double 元素的数组来调用该函数。程序还包含一个具体化,它将 char 指针数组和数组中的指针数量作为参数,并返回最长的字符串的地址。如果有多个这样的字符串,则返回其中第一个字符串的地址。使用由 5 个字符串指针组成的数组来测试该具体化。

代码:

#include <iostream>
#include <cstring>
using namespace std;

#define intSize 6
#define doubleSize 4
#define charSize 5

template <typename T>
T maxn(T arr[], int n)
{
    T t_max = arr[0];
    for (int i = 1; i < n; i++)
    {
        if (arr[i] > t_max)
            t_max = arr[i];
    }
    return t_max;
}

template <>
char *maxn(char *arr[], int n)
{
    const char *s = arr[0];

    for (int i = 1; i < n; i++)
    {
        if (strlen(arr[i]) > strlen(s))
            s = arr[i];
    }
    return s;
}

int main()
{
    int arr1[intSize] = {1, 6, 3, 2, 5, 10};
    double arr2[doubleSize] = {2.3, 5.2, 1.4, 2.7};
    char *arr3[charSize] = {"a", "bb", "ccc", "dddd", "eeeee"};

    cout << "The maximum value in int array is " << maxn(arr1, intSize) << endl;
    cout << "The maximum value in double array is " << maxn(arr2, doubleSize) << endl;
    cout << "The longest string in char array is " << maxn(arr3, charSize) << endl;

    system("pause");
    return 0;
}

运行结果:

在这里插入图片描述

7. SumArray()

修改程序清单 8.14 ,使其使用两个名为 SumArray ()的模板函数来返回数组元素的总和,而不是显示数组的内容。程序应显示thing的总和以及所有 debt 的总和。

代码:

#include <iostream>
using namespace std;

template <typename T> // template A
T SumArray(T arr[], int n);

template <typename T> // template B
T SumArray(T *arr[], int n);

struct debts
{
    char name[50];
    double amount;
};

int main()
{
    int things[6] = {13, 31, 103, 301, 310, 130};
    struct debts me_E[3] =
        {
            {"Ima Wolfe", 2400.0},
            {"Ura Foxe", 1300.0},
            {"Iby Stout", 1800.0}};
    double *pd[3];

    for (int i = 0; i < 3; i++)
        pd[i] = &(me_E[i].amount);

    cout << "Listing Mr.E's counts:" << endl;
    cout << SumArray(things, 6) << endl;

    cout << "Listing Mr.E's debts:" << endl;
    cout << SumArray(pd, 3) << endl;

    system("pause");
    return 0;
}

template <typename T>
T SumArray(T arr[], int n)
{
    T sum = 0;

    cout << "template A\n";
    for (int i = 0; i < n; i++)
        sum += arr[i];

    return sum;
}

template <typename T>
T SumArray(T *arr[], int n)
{
    T sum = 0;

    cout << "template B\n";
    for (int i = 0; i < n; i++)
        sum += *arr[i];

    return sum;
}

运行结果:

在这里插入图片描述

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

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

相关文章

【C++】C++11 异常

目录 1. C语言传统的处理错误的方式 2. C异常概念 3. 异常的使用 3.1. 异常的抛出和捕获 3.2. 在函数调用链中异常栈展开匹配原则 3.3. 异常的重新抛出 3.4. 异常安全 3.5. 异常规范 4.自定义异常体系 5. C标准库的异常体系 6. 异常的优缺点 6.1. C异常的优点&…

Spark性能优化二 Shuffle机制分析

&#xff08;一&#xff09; 什么情况下发生shuffle 在MapReduce框架中&#xff0c;Shuffle是连接Map和Reduce之间的桥梁&#xff0c;Map阶段通过shuffle读取数据并输出到对应的Reduce&#xff1b;而Reduce阶段负责从Map端拉取数据并进行计算。在整个shuffle过程中&#xff0c…

Linux 学习整理(使用 iftop 查看网络带宽使用情况 《端口显示》)

一、命令简介 iftop 是实时流量监控工具&#xff0c;可以用来监控网卡的实时流量&#xff08;可以指定网段&#xff09;、反向解析IP、显示端口信息等。 二、命令安装 yum install -y iftop 三、命令相关参数及说明 3.1、相关参数说明 -i&#xff1a;设定监测的网卡&#…

python未来应用前景怎么样

Python近段时间一直涨势迅猛&#xff0c;在各大编程排行榜中崭露头角&#xff0c;得益于它多功能性和简单易上手的特性&#xff0c;让它可以在很多不同的工作中发挥重大作用。 正因如此&#xff0c;目前几乎所有大中型互联网企业都在使用 Python 完成各种各样的工作&#xff0…

CAD中如何将图形对象转换为三维实体?

有些小伙伴在CAD绘制完图纸后&#xff0c;想要将图纸中的某些图形对象转换成三维实体&#xff0c;但却不知道该如何操作&#xff0c;其实很简单&#xff0c;本节CAD绘图教程就和小编一起来了解一下浩辰CAD软件中将符合条件的对象转换为三维实体的相关操作步骤吧&#xff01; 将…

HID协议详解 - Report Descriptor报告描述符构建与解析

USB相关基础知识简述 报告描述符是HID协议里比较复杂的一部分&#xff0c;在理解报告描述符之前&#xff0c;可以对USB协议数据传输的一些基础知识做一些了解&#xff0c;更方便理解后续内容。 报告是USB协议里数据传输&#xff08;Data Transfer&#xff09;的一种&#xff…

Android正确使用资源res文件

观看此文注意首先有的UI改颜色&#xff0c;没用&#xff0c;发现无法更改按钮背景颜色。我的AS下载的是最新版本&#xff0c;Button按钮的背景颜色一直都是亮紫色&#xff0c;无法更改。为什么呢&#xff1f;首先在你的清单文件中看你应用的是哪个主题。我现在用的是这个可能你…

PYthon组合数据类型的简单使用

Python的数据类型有两种&#xff0c;基本数据类型和组合数据类型&#xff0c;组合数据类型在Python的使用中特别重要。 1.组合数据类型的分类&#xff1a; 2.序列类型 序列类型中元素存在顺序关系&#xff0c;可以存在数值相同但位置不同的元素。序列类型支持成员关系操作符&…

计算机编程基础

0与1的世界 计算机是由晶体管和电路板组成的电子设备。 不论是我们微信信息的呈现、图像的储存和数字之间的运算本质上都是0和1的信息。 0、1便可以代表电压的高低、开关的闭合以及电阻的导电和不导电。 0、1表示的数字便是“逢二进一”。计算机的最小的储存单位是位&#…

Java如何String字符串带括号转成List

问题现象 今天在做一个需求&#xff1a;将存入数据库中的数据读到后解析成list遍历分析 数据格式&#xff1a; "[1677660600000, 1677660900000, 1677661200000]" "[5, 4, 4,3,2&#xff0c;0,0]" 我一开始想到的就是使用逗号分割即可 结果变成了这样的…

电容笔和Apple pencil有什么区别?开学季电容笔排行榜

与苹果的 Pencil相比&#xff0c;市面上常见的电容笔在压感上是没有具备重力压感&#xff0c;只具备着一种倾斜压感。对于绘画没有过高要求的话&#xff0c;其实一支普通的平替电容笔&#xff0c;就能为我们解决日常很多问题。它不仅可以用在办公上&#xff0c;也可以用在笔记、…

算法小抄3-理解使用Python容器之列表

引言 首先说一个概念哈,程序算法数据结构,算法是条件语句与循环语句组成的逻辑结构,而数据结构也就是容器. 算法决定数据该如何处理,而容器则决定如何数据如何存储. 不同的语言对容器有不同的实现方式, 但他们的功能都是相似的, 打好容器基础,你就可以在各式各样的语言中来回横…

1.Spring Cloud (Hoxton.SR10) 学习笔记—基础知识

本文目录如下&#xff1a;一、Spring Cloud基础知识什么是微服务架构&#xff1f;服务拆分 有哪些注意事项&#xff1f;什么是分布式集群?分布式的 CAP 原则&#xff1f;组件 - Spring Cloud 哪几个组件比较重要&#xff1f;组件 - 为什么要使用这些组件&#xff1f;组件 - Na…

有关白盒加密

白盒密码技术白皮书 有关白盒的概念 其实白盒黑盒之类概念其实是软件保护方面的概念&#xff0c;在很多方面都有应用&#xff0c;例如 黑盒&#xff1a; 传统的加密技术是默认假定处于黑盒中的&#xff0c;也就是假定攻击者无法获得密钥。具体而言&#xff0c;认为攻击者并…

PMP证书含金量如何,打算以后从事项目管理这一行业的有没有必要考这个证书?

建议考一个&#xff0c;虽然说这一纸证书实际不能带来多少利益&#xff0c;只是一个资格证书&#xff0c;项目管理行业入门证书&#xff0c;但是现在很多企业招聘要求中写了“有 PMP 证书”优先录取&#xff0c;还是考一个有备无患。含金量问题一直备受关注&#xff0c;总结了一…

操作系统(1.1)--引论

目录 一、操作系统的目标和作用 1.操作系统的目标 2.操作系统的作用 2.1 OS作为用户与计算机硬件系统之间的接口 2.2 OS作为计算机系统资源的管理者 2.3 0S实现了对计算机资源的抽象 3. 推动操作系统发展的主要动力 二、操作系统的发展过程 1.无操作系统的计算机系统…

Web3中文|日本元宇宙经济“狂飙”

2月27日&#xff0c;三菱、富士通和其它科技公司发布关于建立“日本元宇宙经济区”的协议&#xff0c;表示将联手从角色扮演游戏的角度创建开放的元宇宙基础设施&#xff0c;以推动日本的Web3战略。据了解&#xff0c;日本一直在努力将Web3技术纳入其国家议程&#xff0c;去年1…

规范哈夫曼编码和Deflate算法

经过常规的哈夫曼编码以后&#xff0c;我们需要将每个符号对应的码字记录下来&#xff0c;比较容易想到的是按照字母序记录每个字母的编码&#xff0c;这样的好处是字母与码字的映射关系被隐式记录&#xff1a; 假设字母表 A{a1,a2,a3,a4,a5}\mathcal{A}\{a_1,a_2,a_3,a_4,a_5\…

基于数据驱动的电动车电池数据分析(一)

基于数据驱动的电动车电池数据分析&#xff08;一&#xff09; 欢迎关注笔者的微信公众号 笔者过去一年多的时间都在国内一家头部新能源企业实习&#xff0c;主要参与一些数据分析和平台研发的工作。在工作中积累了一些数据分析的经验&#xff0c;其中新能源领域比较多的是一…

曾经被人们看成是异想天开的产业互联网,或许终将会实现

一波还未平息&#xff0c;一波又起。元宇宙的热度还未彻底散去&#xff0c;ChatGPT已经成为了名符其实的新风口。如果用一个概念来定义现在这样一个热点和风口频出的时代的话&#xff0c;我想&#xff0c;用产业互联网或许是再合适不过的了。对此&#xff0c;可能有人并不认同。…