C++大学基础教程第五章-2011课件.ppt
文本预览下载声明
C++大学基础教程;5.1 函数概述 被调,主调;自定义,库
5.2 函数定义 函数调用
5.3 问题1 内联函数 问题2 重载函数
默认参数值的函数
5.4 问题2再分析 函数模板
5.5 全局变量与局部变量
5.6 变量的存储类型 课堂练习
5.7 编译预处理(要求#include, #define) ;一个例子;5.1 函数概述 ;#include iostream
#include cmath
using namespace std;
int main() {
cout Enter Quadratic coefficients: ;
double a, b, c;
cin a b c;
if ( (a != 0) (b*b - 4*a*c 0) )
{
double radical = sqrt(b*b - 4*a*c);
double root1 = (-b + radical) / (2*a);
double root2 = (-b - radical) / (2*a);
cout Roots: root1 root2;
}
else
{
cout Does not have two real roots;
}
return 0;
};#include iostream
using namespace std;
float CircleArea(float r);
// main(): manage circle computation
int main() {
cout Enter radius: ;
float MyRadius;
cin MyRadius;
float Area = CircleArea(MyRadius);
cout Circle has area Area;
return 0;
}
// CircleArea(): compute area of radius r circle
float CircleArea(float r) {
const float Pi = 3.1415;
return Pi * r * r;
};int main函数
{ ……
调用函数 CircleArea(float r);
……
};⑴ 一个C++源程序可以由一个或多个源程序文件组成。C++编译系统在对C++源程序进行编译时是以文件为单位进行的。
⑵ 一个C++源程序文件可以由一个或多个函数组成。所有函数都是独立的。主函数可以调用其它函数,其它函数可以相互调用。
⑶ 在一个C++程序中,有且仅有一个主函数main。C++序的执行总是从main函数开始,调用其它函数后最终回到main函数,在main函数中结束整个程序的运行。;2.数学库函数
C++语言提供的库函数中有一些是专门完成特定的数学运算的,称为数学库函数。
实现常见的数学计算
例如: 求绝对值、平方根等。
调用数学函数: 函数名(参数1,…,参数n)
平方根函数: sqrt(x)
例如: coutsqrt(900.0);;2.数学库函数
数学函数库中的多数函数都返回double类型结果。
使用数学库函数,需要在程序中包含math.h头文件,这个头文件在新的C++标准库中称为cmath。
函数参数可取常量、变量或表达式。
例: 如果c=13.0、d=3.0和f=4.0,则下列语句:
coutsqrt(c+d*f);
计算并显示13.0+3.0*4.0=25.0的平方根,即5.0。 ;5.2 函数定义;函数的定义;
float CircleArea (float r)
{
const float Pi = 3.1415;
return Pi * r * r;
}
;函数名;Sum();形式参数表;Sum();PromptAndRead();函数返回值;Sum();示例2:;函数体;Sum();int max(int x,int y)
{ int z;
z = x y ? x : y;
return( z );
};5.3 函数调用 ;函数原型 ;函数原型 ;函数原型 ;函数原型 ;函数原型 ;函数原型 ;void subfun1(…);//原型声明
main()
{
┆
subfun1(…);//函数调用
┆
}
void subfun2()
{
┆
subfun1(…);//函数调用
┆
}
void subfun1(…)//函数定义
{
显示全部