C++Primer Plus 7

结构体的练习

// 结构体成员有 时,分。函数计算两个结构体的值
#include
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 
#include 
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

你可能感兴趣的:(C++)