《C++ primer plus》第3章练习题

注:有的题设条件自己改动了一下,比如英寸英尺改成米和厘米,部分题目自己加了点额外要求。

1.要求用户输入身高(m),用下划线提示用户输入,将身高转化成“米“加“厘米”的形式输出,用const限定符设定转化因子。

#include<iostream>

using namespace std;

const int cvt = 1;

int main()
{
	char s = '_';

	double input_height;

	cout << "Enter your height(m):" << s << s;

	cin >> input_height;

	cout << "Your height is:" << int(input_height) / cvt << "m plus " << 100*(input_height - int(input_height)) << "cm." << endl; 

	system("pause");

}

 

2.要求用户输入身高(m)和体重(kg),计算其BMI指数,并判断其健康程度。

#include<iostream>

using namespace std;

const double index1 = 18.5, index2 = 23.9, index3 = 27.0, index4 = 32.0;

int main()
{
	double input_height,input_weight,BMI_index;

	cout << "Enter your height(m):" << endl;

	cin >> input_height;

	cout << "Enter your weight(kg):" << endl;

	cin >> input_weight;

	BMI_index = input_weight / (input_height*input_height);

	cout << "Your BMI index is " << BMI_index << endl;

	if (BMI_index < index1)
		cout << "underweight
";
	else if ((BMI_index >= index1) && (BMI_index < index2))
		cout << "normal weight
";
	else if ((BMI_index >= index2) && (BMI_index < index3))
		cout << "overweight
";
	else if ((BMI_index >= index3) && (BMI_index < index4))
		cout << "obese
";
	else 
		cout << "extrmely obese
";

	system("pause");

}

 

3.要求用户输入秒数,计算其天数+小时数+分钟数+秒数的结果并输出(如“31600000 秒 = 365 天,17小时,46分钟,40秒”)。

#include<iostream>

using namespace std;

const long S2M = 60,S2H = 3600,S2D = 86400; 

int main()
{
	long long input_seconds;

	int seconds,minutes,hours,days;

	cout << "Enter the number of seconds:";

	cin >> input_seconds;

	days = input_seconds / S2D;
	hours = (input_seconds % S2D) / S2H;
	minutes = ((input_seconds % S2D) % S2H) / S2M;
	seconds = ((input_seconds % S2D) % S2H) % S2M;

	cout << input_seconds << " seconds = ";
	cout << days << " days," << hours << " hours," << minutes << " minutes," << seconds << " seconds.";

	system("pause");

}

  

原文地址:https://www.cnblogs.com/banmei-brandy/p/11247029.html