image.png
-
C++函数分为有返回值和没有返回值的
image.png -
有返回值的函数生成一个值,这个值可以赋给变量或在其他表达式使用。
image.png - 可以把函数当作是一个机器,机器需要喂什么 ,然后吐出来什么,吐出来的东西,还可以充当其他机器食物。
- C++编译器必须知道函数的参数类型和返回值类型,也就是说必须知道机器要吃什么种类的东西,和吐出来什么。通过函数原型来告诉编译器需要哪些信息。
- 函数原型,函数 等同于 变量声明 与变量的关系。
- 原型是一条语句,所以必须用分号来结束。
-
如果省略分号,编译器会将代码解释为一个函数头,并要求该函数提供函数体。
image.png - 提供原型的方法
- 在源代码文件中输入函数原型。
- 包含头文件中定义了原型。
- 建议使用头文件的形式来指明函数原型。
-原型只是描述函数接口,即发送给函数的信息和函数返回的信息。 - 函数的定义,描述函数的接口和怎么加工发送给函数的信息。
- 库文件包含函数的编译代码
- 头文件包含函数的原型。
- 通常把函数原型的声明放在main函数定义的前面。在使用函数之前提供函数的原型。
#include<iostream>
#include<cmath>
int main(int argc, char const *argv[])
{
using namespace std;
double area;
cout << "Enter the floor area ,in square feet,of your home:" ;
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;
}
运行结果:
D:\C++pratice\c++ Primer plus>g++ 2.4.cpp -g
D:\C++pratice\c++ Primer plus>a.exe
Enter the floor area ,in square feet,of your home:1536
That's the equivalent of a square 39.1918 feet to the side .
How fascinating!
image.png
- 声明变量
- 类型 变量名
- C++允许程序在任何地方声明新变量
-
创建变量时对其进行赋值叫做对变量的初始化
image.png - 有些函数需要喂多种数据,不同种类的数据用逗号隔开。
- 有些机器不需要喂数据,可以使用void,也可以不写。
- 使用函数的使用必须包括括号,因为函数名只是一个地址。
- 没有返回值的函数,不能在调用后赋给赋值语句或其他表达式中。
- 在有些语言中,有返回值的叫做函数,没有返回值的叫做过程。
- 标准C库提供了140个预定义的函数。
- 但是在设计其他东西时,用户往往需要自己编写函数。
-每个C++程序都必须有一个main()函数
#include<iostream>
void simon(int n );
int main(int argc, char const *argv[])
{
using namespace std;
simon(3);
cout << "Pick an integer:";
int count;
cin >> count;
simon(count);
cout << "Done!" << endl;
return 0;
}
void simon(int n)
{
using namespace std;
cout << "Simon says touch your toes " << n << " times ." << endl;
}
结果显示:
D:\C++pratice\c++ Primer plus>a.exe
Simon says touch your toes 3 times .
Pick an integer:512
Simon says touch your toes 512 times .
Done!
D:\C++pratice\c++ Primer plus>
image.png
image.png
image.png
image.png