C++Primer Plus 7

11238 ワード

構造体の練習
//         , 。           
#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;
}

2 D座標と極座標変換2 Dざひょうへんかん
#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 .
"
; 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