C++ primer plus (第六版)第七章strctfun.cpp代码及解释

本文详细介绍了如何使用C++中的自定义结构体进行矩形坐标到极坐标的转换,并展示了如何将这些结构体作为参数传递给函数。通过具体示例,深入理解结构体在C++中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

如有失误之处,还恳请指教!!!

// strctfun.cpp -- functions with a structure argument
#include <iostream>
#include <cmath>

// structure declarations
//结构声明
struct polar
{
    double distance;      // distance from origin
    double angle;         // direction from origin
};
struct rect
{
    double x;             // horizontal distance from origin
    double y;             // vertical distance from origin
};

// prototypes
//函数原型:返回值为自定义类型polar类型,含有一个参数,参数类型为自定义rect类型
polar rect_to_polar(rect xypos);
//函数原型:没有返回值,含有一个参数,参数类型为自定义polar类型
void show_polar(polar dapos);

int main()
{
    using namespace std;
    //声明自定义类型rect和polar类型的变量
    rect rplace;
    polar pplace;

    cout << "Enter the x and y values: ";
    //这里使用的依然是将cin作为判断条件
    while (cin >> rplace.x >> rplace.y)  // slick use of cin
    {
        //调用rect_to_polar()函数并将rplace作为实际参数传递,将rect_to_polar的返回值赋值给
        //自定义类型变量
        pplace = rect_to_polar(rplace);
        show_polar(pplace);
        cout << "Next two numbers (q to quit): ";
    }
    cout << "Done.\n";
    return 0;
}

// convert rectangular to polar coordinates
polar rect_to_polar(rect xypos)
{
    using namespace std;
    polar answer;

    answer.distance =
        sqrt( xypos.x * xypos.x + xypos.y * xypos.y);
    answer.angle = atan2(xypos.y, xypos.x);
    return answer;      // returns a polar structure
}

// show polar coordinates, converting angle to degrees
void show_polar (polar dapos)
{
    using namespace std;
    const double Rad_to_deg = 57.29577951;

    cout << "distance = " << dapos.distance;
    cout << ", angle = " << dapos.angle * Rad_to_deg;
    cout << " degrees\n";
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值