3.燃烧我的卡路里.小明(130斤)和小红(100斤)决定减肥,请你编写 类和对象实现这一过程: ①吃东西(eat)增重 1斤②跑步(run)减重 0.5斤 ③小明跑步三次进食一次,小红跑步两次进食两次,请判断他们是否 减肥成功
时间: 2024-02-15 08:05:53 浏览: 76
可以设计一个类来表示人,其中包括体重、卡路里消耗和卡路里摄入量等属性,以及吃东西和跑步等方法。具体实现如下:
```c++
#include <iostream>
using namespace std;
class Person {
public:
Person(double weight, double calorie) {
this->weight = weight;
this->calorie = calorie;
this->calorieIntake = 0.0;
this->calorieBurned = 0.0;
}
void eat() {
calorieIntake += 1.0;
weight += 1.0;
}
void run() {
calorieBurned += 0.5;
weight -= 0.5;
}
void checkWeight() {
if (weight <= targetWeight) {
cout << "减肥成功!" << endl;
} else {
cout << "减肥失败!" << endl;
}
}
void process() {
if (this->weight <= targetWeight) {
return;
}
if (this->name == "小明") {
if (runCount % 3 == 0) {
eat();
} else {
run();
}
} else if (this->name == "小红") {
if (runCount % 2 == 0) {
eat();
} else {
run();
}
}
runCount++;
process();
}
void setName(string name) {
this->name = name;
}
void setTargetWeight(double targetWeight) {
this->targetWeight = targetWeight;
}
private:
double weight; // 体重
double calorie; // 单位体重卡路里消耗
double calorieIntake; // 卡路里摄入量
double calorieBurned; // 卡路里消耗量
double targetWeight; // 目标体重
int runCount = 0; // 跑步次数或者进食次数
string name; // 姓名
};
int main() {
Person xiaoming(130.0, 0.05);
xiaoming.setName("小明");
xiaoming.setTargetWeight(120.0);
xiaoming.process();
xiaoming.checkWeight();
Person xiaohong(100.0, 0.06);
xiaohong.setName("小红");
xiaohong.setTargetWeight(90.0);
xiaohong.process();
xiaohong.checkWeight();
return 0;
}
```
其中,eat 方法会增加卡路里摄入量和体重,run 方法会增加卡路里消耗量和减少体重。process 方法根据小明和小红的不同规律进食和跑步,直到达到目标体重。checkWeight 方法会判断是否达到目标体重。在 main 函数中,我们分别创建了小明和小红的对象,并设置了目标体重。调用 process 方法来进行减肥过程,最后调用 checkWeight 方法判断是否成功减肥。
阅读全文