打卡cs106x(Autumn 2017)-lecture2
1、BMI
Write a complete C++ program with a main
function to calculate 2 people's body mass index (BMI), using the following formula:
BMI = weight / height2 * 703
The BMI rating groups each person into one of the following four categories:
BMI | Category |
---|---|
below 18.5 | class 1 |
18.5 - 24.9 | class 2 |
25.0 - 29.9 | class 3 |
30.0 and up | class 4 |
Match the following example output:
This program reads data for two people
and computes their body mass index (BMI).Enter Person 1's information:
height (in inches)? 70.0
weight (in pounds)? 194.25
BMI = 27.8689, class 3Enter Person 2's information:
height (in inches)? 62.5
weight (in pounds)? 130.5
BMI = 23.4858, class 2BMI difference = 4.3831
You should break down your program into several functions, each of which helps solve the overall problem.
解答:
#include <iostream>
#include "console.h"
#include "simpio.h"using namespace std;void inputHeightAndWeight(double& h, double& w);
void calcuBmi(double& h, double& w, double& b);
void calcuClass(double& b, int& c);
void bmiDiff(double& b1, double& b2);int main() {cout << "This program reads data for two people" << endl;cout << "and computes their body mass index (BMI)." << endl << endl;double h1, w1, b1, h2, w2, b2;int c1, c2;for (int i = 1; i < 3; i++) {cout << "Enter Person " << i << "'s information:" << endl;if (i == 1) {inputHeightAndWeight(h1, w1);calcuBmi(h1, w1, b1);calcuClass(b1, c1);} else {inputHeightAndWeight(h2, w2);calcuBmi(h2, w2, b2);calcuClass(b2, c2);}}bmiDiff(b1, b2);return 0;
}void inputHeightAndWeight(double& h, double& w) {h = getDouble("height (in inches)? ");w = getDouble("weight (in pounds)? ");
}void calcuBmi(double& h, double& w, double& b) {b = w / (h * h) * 703;cout << "BMI = " << b << ", ";
}void calcuClass(double& b, int& c) {if (b < 18.5) {c = 1;} else if (b < 25.0) {c = 2;} else if (b < 30.0) {c = 3;} else {c = 4;}cout << "class " << c << endl << endl;
}void bmiDiff(double& b1, double& b2) {cout << "BMI difference = ";if (b1 > b2) {cout << b1 - b2;} else{cout << b2 - b1;}
}
2、stringMysteryAB
What is the output of the following code?
解答:
marty steFOOppa
3、nameDiamond
Write a function named nameDiamond
that accepts a string as a parameter and prints it in a "diamond" format as shown below. For example, the call of nameDiamond("MARTY");
should print:
M
MA
MAR
MART
MARTYARTYRTYTYY
解答:
#include <iostream>
#include <string>
#include "console.h"
#include "simpio.h"using namespace std;void nameDiamond(string s) {int len = s.length();// 上半部分for (int i = 0; i < len; i++) {cout << s.substr(0, i + 1) << endl;}// 下半部分for (int i = 1; i < len; i++) {// 空格for (int j = 0; j < i; j++) {cout << " ";}cout << s.substr(i, len - i) << endl;}
}int main() {string name = getLine("Enter your name: ");nameDiamond(name);return 0;
}