読者です 読者をやめる 読者になる 読者になる

個人的自由ノート

ふと自分が気になった事を書いてます

C++で問題を解く

問題集もそろそろ終わりに近づいてきました。次はデータ構造とアルゴリズムについてやっていこうかなと思ってます。やっと本格的な話題だ…。

#include <iostream>
#include <cmath>
#include <string>

class Car{
    std::string name;
    std::string number;
    int width;
    int length;
    int height;
    double x;
    double y;
    double sfc;
    double tankage;
    double fuel;

public:
    Car(std::string n, std::string no, int w, int l, int h, double s, double t, double f){
        this->name = n;
        this->number = no;
        this->width = w;
        this->length = l;
        this->height = h;
        this->sfc = s;
        this->tankage = t;
        this->fuel = f <= this->tankage ? f : this->tankage;
        this->x = this->y = 0.0;
    }

    double getX() { return this->x; }
    double getY() { return this->y; }
    double getFuel() { return this->fuel; }
    
    void print_spec() {
        std::cout << "名前 = " << this->name << std::endl;
        std::cout << "ナンバー = " << this->number << std::endl;
        std::cout << "車幅 = " << this->width << std::endl;
        std::cout << "車長 = " << this->length << std::endl;
        std::cout << "車高 = " << this->height << std::endl;
        std::cout << "燃費 = " << this->sfc << std::endl;
        std::cout << "タンク容量 = " << this->tankage << std::endl;
    }

    bool move(double dx, double dy){
        double dist = sqrt(dx * dx + dy * dy);
        double f = dist / sfc;
        if(f > fuel)
            return false;
        else {
            fuel -= f;
            this->x += dx;
            this->y += dy;
            return true;
        }
    }

    void refuel(double df){
        if(df > 0) {
            fuel += df;
            if(fuel > tankage)
                fuel = tankage;
        }
    }
};

int main(void){
    std::string name, number;
    int width, length, height;
    double sfc, tankage, fuel;

    std::cout << "車のデータを入力せよ。" << std::endl;
    std::cout << "名前 : "; std::cin >> name;
    std::cout << "ナンバー : "; std::cin >> number;
    std::cout << "車幅 : "; std::cin >> width;
    std::cout << "車長 : "; std::cin >> length;
    std::cout << "車高 : "; std::cin >> height;
    std::cout << "燃費 : "; std::cin >> sfc;
    std::cout << "タンク容量 : "; std::cin >> tankage;
    std::cout << "ガソリン量 : "; std::cin >> fuel;

    Car myCar(name, number, width, length, height, sfc, tankage, fuel);
    myCar.print_spec();

    while(true){
        std::cout << "現在地(" << myCar.getX() << ", " << myCar.getY() << ")" << std::endl;
        std::cout << "残り燃料 : " << myCar.getFuel() << "リットル" << std::endl;
        std::cout << "移動[0...No/1...Yes] : ";
        int move;
        std::cin >> move;
        if(move == 0) break;

        double dx, dy;
        std::cout << "X方向の移動距離 : "; std::cin >> dx;
        std::cout << "Y方向の移動距離 : "; std::cin >> dy;
        if(!myCar.move(dx, dy))
            std::cout << "\a燃料が足りません!\n";
    }

    return 0;
}