showMe()呼び出し例: 名前:yamada taro 身長:165cm 体重:65kg の場合 ==== Profile ==== 名前:yamada taro 身長:165 cm 体重:65 kg BMI:23.8 =================
#pragma once #include <iostream> #include <string> using std::string; class cStudent { private: //プライベートメンバとして、 //名前、身長、体重がある string m_name;//名前:string型 float m_height;//身長:小数点数 float float m_weight;//体重:小数点数 float public: cStudent(); cStudent(string _name, float _height, float _weight); string getMyName(); float getMyHeight(); float getMyWeight(); void setMyName(string _name); void setMyHeight(float _height); void setMyWeight(float _weight); float calcBMI(); void printMe(); };
#include "cStudent.h" using std::cout; using std::endl; using std::pow; cStudent::cStudent() { this->m_name = ""; this->m_height = 0.0; this->m_weight = 0.0; } cStudent::cStudent(string _name, float _height, float _weight) { this->m_name = _name; this->m_height = _height; this->m_weight = _weight; //cout << "Constructer with Arguments has called." << endl; } //引数でもらってきた名前をメンバにセット void cStudent::setMyName(string _name) { this->m_name = _name; } //引数でもらってきた身長をメンバにセット void cStudent::setMyHeight(float _height) { this->m_height = _height; } //引数でもらってきた体重をメンバにセット void cStudent::setMyWeight(float _weight) { this->m_weight = _weight; } string cStudent::getMyName() { return(this->m_name); } float cStudent::getMyHeight() { return(this->m_height); } float cStudent::getMyWeight() { return(this->m_weight); } //メンバ変数の体重と身長を使って //BMIを計算する 体重/身長^2 kg/(m^2) //どうして、iostreamにpowが入っているのかは謎 float cStudent::calcBMI() { //float res = this->m_weight / pow(this->m_height / 100.0, 2); //return res; return(this->m_weight / pow(this->m_height / 100.0, 2)); } void cStudent::printMe() { cout << "==== Profile of " << this->m_name << " ====" << endl; //cout << "名前:" << this->m_name << endl; cout << "身長:" << this->m_height << " cm" << endl; cout << "体重:" << this->m_weight << " kg" << endl; cout << "BMI:" << this->calcBMI() << endl; cout << "=================" << endl; }
#include "cStudent.h" #include <iostream> #include <vector> int main() { using std::cin; using std::cout; using std::endl; using std::vector; cStudent s[2] = { {"太郎",170.0,66.0}, {"次郎",168.0,72.0} }; for (int i = 0; i < 2; i++) { s[i].printMe(); } }
main関数内で以下のようなデータを読み込んで、クラスのメンバに値をセットしなさい。
人数分のclassの配列を作って、for分でデータを読み込む!
初めの数字はデータ数、その後に学生のデータが1行に1人分ずつ並んでいる
9 yamada 165 65 imada 156 84 kagawa 172 76 shibata 148 45 muto 182 95 okada 185 105 nagata 178 82 suzuki 179 88 akiyama 185 90
main関数の前部分に関数を二つ作りなさい。
これらの関数を使い、並べ替えられたプロフィール一覧を表示しなさい。
これって何ソーティングだっけ?
sortByWeightは自分で考えてみよう!
それと、昇順降順の切り替えも考えてみましょう!
//オブジェクト(cStudent型)の配列を身長で並べ替える関数 //昇順にしようかな? void sortByHeight(cStudent *_stu, int n); //オブジェクト(cStudent型)の配列を体重で並べ替える関数 //昇順にしようかな? void sortByHeight(cStudent* _stu, int n) { cStudent v; int j; for (int i = 1; i < n; i++) { v = _stu[i]; j = i - 1; while (j >= 0 && _stu[j].getMyHeight() > v.getMyHeight()) { _stu[j + 1] = _stu[j]; j--; } _stu[j + 1] = v; } }