C++ Primer Plus 第七章答案

这篇博客提供了多个C++编程练习,涵盖了数组操作、结构体的使用、递归函数实现以及函数指针的应用。练习包括计算调和平均数、处理高尔夫成绩、显示和操作box结构、计算彩票中奖几率、阶乘函数、数组填充与反转、指针区间处理、使用结构存储季度开支等,旨在提升C++编程能力。
摘要由CSDN通过智能技术生成

7.13.1编写一个程序,不断要求用户输入两个数,直到其中一个为0。对于每两个数,程序将使用一个函数来计算它们的调和平均数,并将结果返回给main(),而后者将报告结果。调和平均数指的是倒数平均值的倒数,计算公式如下:
调和平均数 = 2.0 * x * y / (x + y)

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

double getHarmonic(double x, double y);

int main()
{
    cout<<"Enter two numbers: ";
    double x, y;
    while(cin>>x>>y)
    {
        if(x == 0 || y == 0)        break;
        cout<<"The harmonic average is "<<getHarmonic(x, y)<<endl;
        cout<<"Next enter: ";
    }
    return 0;
}

double getHarmonic(double x, double y)
{
    return 2.0 * x * y / (x + y);
}

7.13.2编写一个程序,要求用户输入最多10个高尔夫成绩,并将其存储在一个数组中。程序允许用户提早结束输入,并在一行上显示所有成绩,然后报告平均成绩。请使用3个数组处理函数来分别进行输入、显示和计算平均成绩。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

int input(double score[], int MaxSize);
void show(const double score[], int ActSize);
double getAverage(const double score[], int ActSize);

int main()
{
    double score[10];
    int number = input(score, 10);
    show(score, number);
    double average = getAverage(score, number);
    cout<<"The average score is : "<<average<<endl;
    return 0;
}

int input(double score[], int Size)
{
    cout<<"Enter the all score of the golf: ";
    int i=0;
    while(cin>>score[i] && i < Size)
        i++;
    return i;
}

void show(const double score[], int ActSize)
{
    cout<<"The all score is: ";
    for(int i=0;i<ActSize;i++)
        cout<<score[i]<<"\t";
    cout<<endl;
}

double getAverage(const double score[], int ActSize)
{
    double average =0, sum =0;
    for(int i=0;i<ActSize;i++)
        sum += score[i];
    return sum / ActSize;
}

7.13.3下面是一个结构声明:
struct box
{
char maker[40];
float height;
float width;
float length;
float volume;
};
a.编写一个函数,按值传递box结构,并显示每个成员的值
b.编写一个函数,传递box结构的地址,并将volume成员设置为其他三维长度的积
c.编写一个使用这两个函数的简单程序。

#include <iostream>
using std::cout;
using std::cin;
using std::endl;

struct box
{
    char maker[40];
    float height;
    float width;
    float length;
    float volume;
};

void showData(const box b);
void setData(box *b);

int main()
{
    box b = { "yang", 5, 6, 
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值