📄 pex3_14.cpp
字号:
#include <iostream.h>
#include <iomanip.h>
class Baseball
{
private:
// data members
int playerno;
int atbats;
int hits;
float batave;
// private method. compute batting average
float ComputeBatAve (void)
{
// if no player number or player has no at bats, return 0
if (playerno == -1 || atbats == 0)
return 0;
else
// return batting average
return float(hits)/atbats;
}
public:
// constructor with default parameters
Baseball(int n = -1, int ab = 0, int h = 0);
// data access operations
void ReadPlayer(void);
void WritePlayer(void) const;
float GetBatAve(void) const;
};
// constructor. assign data members
Baseball::Baseball(int n, int ab, int h):
playerno(n), atbats(ab), hits(h)
{
// call ComputeBatAve to assign batting average
batave = ComputeBatAve();
}
// read player information
void Baseball::ReadPlayer(void)
{
// if object not initialized, read player number
if (playerno == -1)
{
cout << "Player number: ";
cin >> playerno;
}
// read at bats, hits and compute batting average
cout << "Player " << playerno << " at bats: ";
cin >> atbats;
cout << "Hits: ";
cin >> hits;
batave = ComputeBatAve();
}
// print player number and batting average
void Baseball::WritePlayer (void) const
{
// set fill character to '0'
cout.fill('0');
// print the data
cout << "Player: " << playerno << " Average: "
<< setw(3) << int(batave*1000)<< endl;
// reassign fill character to blank
cout.fill(' ');
}
// return the batting average
float Baseball::GetBatAve(void) const
{
return batave;
}
void main(void)
{
// define four Baseball objects
Baseball Catcher(10,100,30), Shortstop(44), Centerfielder, Maxobject;
// read information for Shortstop and Centerfielder.
Shortstop.ReadPlayer();
Centerfielder.ReadPlayer();
cout << endl;
// print information for all players
Catcher.WritePlayer();
Shortstop.WritePlayer();
Centerfielder.WritePlayer();
cout << endl;
// assign Maxobject the value Catcher. then compare the batting
// average stored in Maxobject with those of the other two objects,
// reassigning Maxobject if a larger average is found. Maxobject will
// contain the player with the highest batting average
Maxobject = Catcher;
if (Shortstop.GetBatAve() > Maxobject.GetBatAve())
Maxobject = Shortstop;
if (Centerfielder.GetBatAve() > Maxobject.GetBatAve())
Maxobject = Centerfielder;
cout << "Player with the highest average: ";
Maxobject.WritePlayer();
}
/*
<Run>
Player 44 at bats: 2000
Hits: 185
Player number: 25
Player 25 at bats: 3200
Hits: 1000
Player: 10 Average: 300
Player: 44 Average: 092
Player: 25 Average: 312
Player with the highest average: Player: 25 Average: 312
*/
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -