C++ Primer Plus 代码学习解析(第二章 2.4—2.6)

2.4 sqrt.cpp

#include <iostream>
#include <cmath>

int main()
{
	using namespace std;

	double area;
	cout << "Enter the floor area, in square feet, of your home: " << endl;
	cin >> area;
	double side;
	side = sqrt(area);
	cout << "That's the equivalent of a square " << side
	    << " feet to the side." << endl;
	cout << "How fascinating!" << endl;
	return 0;
}
  1. 本代码主要讲解了c++math库的使用以及开平方的例子。
  2. 首先是开始math库的调用,涉及到头文件的命名约定,c++旧式风格是math.h,而新式风格则为math(无拓展名)、cmath(前面加上c)这两种,一般用第二种:cmath,这种命名也可以使用不是c的特性。
  3. 之后则是sqrt开平方函数的使用。
  4. 最后area和side应为double(浮点)类型,以适应sqrt函数。

2.5 ourfunc.cpp

#include <iostream>

void simon(int n)
{
	using namespace std;

	cout << "Simon says touch your toes " << n << " times." << endl;

}
int main()
{
	using namespace std;

	simon(3);
	cout << "Pick an intger " << endl;
	int count;
	cin >> count;
	simon(count);
	cout << "Done!" << endl;
	return 0;
}
  1. 此代码演示了c++中用户定义无返回值函数的情景,与c采用的格式相同;
  2. main函数两次调用simon函数,一次参数为3,另一次为变量count。

2.6 convent.cpp

#include <iostream>

int stonetolb (int sts)
{
	return 10 * sts;
}
int main()
{
	using namespace std;
	int stone;
	cout << "Enter the weight in stone: " << endl;
	cin >> stone;
	int pounds = stonetolb(stone);
	cout << stone << " stone = " << pounds << "pounds." << endl;
	return 0;
}
  1. 此代码演示了有返回值的函数的使用方法,与c语言相同。
  2. int pounds = stonetolb(stone)表示在定义变量时可直接对其赋值。

  • 7
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值