栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > C/C++/C#

2021-10-20

C/C++/C# 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

2021-10-20

C++练习

把C++Plus的基础看了看,感觉不写代码还是不行,找到了贺利坚老师的博客例题,这里把我写的代码做个保存,也与答案做个对照。
链接: C++程序设计课程主页-2015级.

第二周习题 一、胖子不想说体重
以下为题目要求:

成年男性的标准体重公式为:标准体重(kg)=身高(cm)−100
  超标准体重20%为超重,比标准体重轻20%为超轻。请编写C++程序,输入身高和体重,完成下面的任务:
  (1)计算并输出标准体重。
  (2)计算出标准体重,当超重时,请给出提示。
  (3)计算出标准体重,当超重时给出提示,不超重时也给提示。
  (4)计算出标准体重,输出体重状态(正常/超重/超轻)
  调试完程序,请发布博文,作为上机报告。
解答:
思路:首先是得到输入,然后用判断语句来指向不同结果。
代码如下

#include 
#include 

using namespace std;

void week_2_2() {

	float weight_in = 0;
	float height_in = 0;
	float standard_w = 0;
	float percent_w = 0;
	cout << "请输入你的体重/kg:n";
	cin >> weight_in;
	cout << "请输入你的身高/cm:n";
	cin >> height_in;
	cout << "你的体重是:" << weight_in << "kg" << endl;
	standard_w = height_in - 100;
	cout << "你的标准体重应是:" << standard_w << "kg" << endl;
	float standard_wmax = standard_w * 1.2;
	float standard_wmin = standard_w * 0.8;
	if (weight_in <= standard_wmax && weight_in >= standard_wmin)
		cout << "你的体重正常" << endl;
	else 
		if (weight_in > standard_wmax)
			cout << "你的体重偏重" << endl;
		else
			cout << "你的体重偏轻" << endl;
int main() {

	cout << "第三章习题"< 

跟标准答案对照后,确实是答案要精简一点。

小试循环

写出实现下面求解任务的程序【提示:m是一个变量,在程序中输入】
  (1)求1到m的平方和
  (2)求1到m间所有奇数的和
  (3)求1到m的倒数和,即
  
代码如下:

#include 
#include 
#include 
void week_2_3() {
	int input_num;
	double result_1 = 0, result_2 = 0, result_3 = 0, result_4 = 0, result_5 = 1;
	cout << "please input a integer number:" << endl;
	cin >> input_num;
	for (double i = 1.0; i <= input_num; i++)
	{
		result_1 = result_1 + pow(i, 2);//计算1-m的平方和
		int n = int(i);
		if (n % 2 == 1)//计算1-m所有奇数的和
		{
			result_2 = result_2 + i;
		}
		result_3 = result_3 + (1.0 / i);//计算1-m的倒数和
		result_4 = result_4 + pow(-1, i + 1) * double(1.0 / i);//求(4)
		result_5 = result_5 * i;//求m!
	}
	cout << "1-m的平方和:" << result_1 << endl;
	cout << "计算1-m所有奇数的和:" << result_2 << endl;
	cout << "计算1-m的倒数和:" << result_3 << endl;
	cout << "求(4):" << result_4 << endl;
	cout << "求m!:" << result_5 << endl;
}

int main() {

	cout << "第三章习题"< 

与答案相对比,确实发现了几个需要注意的重点,主要是类型转换会发生的损失,尤其是double>int>double转化时会出现数据丢失,在进行小数计算时容易导致错误,尤其注意代码中(1.0/i),在C++Primer Plus6里找到原因。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/347474.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号