C++Primer Plus 7

结构体的练习

// 结构体成员有 时,分。函数计算两个结构体的值
#include<iostream>
struct travel_time
{
    int hour;
    int min;
};
const int minsPreHr = 60; // hour to min;
travel_time SumTial(travel_time t1, travel_time t2);
void Show(travel_time sum);
int main()
{
    using namespace std;
    travel_time day1 = {5, 45};
    travel_time day2 = {4, 55};
    travel_time trip = SumTial(day1, day2);
    cout << "Tow day total" << endl;
    Show(trip);
}
travel_time SumTial(const travel_time t1, const travel_time t2)
{
    travel_time temp;
    temp.min = (t1.min + t2.min) % minsPreHr;
    temp.hour = (t1.min + t2.min) / minsPreHr + t1.hour + t2.hour;
    return temp;
}

void Show(travel_time sum) 
{
    using namespace std;
    cout << sum.hour<<" hour:"<< sum.min << " min"<<endl;
}

二维坐标和极坐标转换

#include <iostream>
#include <cmath>
using namespace std;
struct Rect
{
    double x;
    double y;
};

struct Polar
{
    double distance;
    double angle;
};

Polar RectToPolar(Rect t1);
void Show(Polar t2);
int main()
{
    cout << "enter the x,y value:" << endl;
    Polar pplace;
    Rect xypose;
    while (cin >> xypose.x >> xypose.y)
    {
       pplace = RectToPolar(xypose);
       Show(pplace);
       cout << "Next to numbers (q to quit)" << endl;
    }
    cin.clear(); // clear buffer
    cout << "Done .\n";
    return 0;
    
}

Polar RectToPolar(Rect t1) 
{
    Polar temp;
    temp.distance = sqrt(t1.y * t1.y +t1.x * t1.x);
    temp.angle = atan2(t1.y, t1.x);
    return temp;
}
void Show(Polar t2)
{
    cout << "distance = " << t2.distance << " angle = " \
    << t2.angle << endl;
}

注意使用 g++ 编译时有些编译库需要被明确指示后才搜索数学库,例如

g++ struct.cpp -lm
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值