这篇主要讲C++中的函数
1.函数的定义
求长方形的面积
#include<iostream>
using namespace std;
int main()
{
float A,B,S;
cout<<"Please inout the length and width of the rectangle:";
cin>>A>>B;
float area(float a,float b);//声明函数
S=area(A,B);
cout<<"The area is:"<<S<<endl;
}
float area(float a,float b)
{
float z;
z=a*b;
return z;
}
2.函数的调用
利用函数调用求长方形的面积
#include<iostream>
using namespace std;
float length,width,square;
void sayHi()
{
cout<<"Please input:";
}
void input(float a,float b)
{
length=a;
width=b;
}
int main()
{
sayHi();
float a,b;
cin>>a>>b;
input(a,b);
void output();//声明函数
output();//调用函数
}
void output()
{
square=length*width;
cout<<"The area is:"<<square<<endl;
}
3.函数的参数传递
(1)值传递
两个变量的值交换—一个错误的程序
/**
两个变量的值交换(一个错误的程序)
*/
#include<iostream>
using namespace std;
void Destroy(int a,int b)
{
int k;
k=a;
a=b;
b=k;
}/*Destroy()*/
int main()
{
int a,b;
cout<<"Please input two integer number:";
cin>>a>>b;
Destroy(a,b);
cout<<a<<","<<b<<endl;
return 0;
} /*main()*/
(2)引用型变量传递
两个变量的值交换
/**
两个变量的值交换
*/
#include<iostream>
using namespace std;
void Destroy(int &a,int &b)
{
int k;
k=a;
a=b;
b=k;
}
int main()
{
int a,b;
cout<<"Please input two integer numbers:";
cin>>a>>b;
Destroy(a,b);
cout<<a<<","<<b;
return 0;
}
4.内联函数
利用内联函数求三角形的面积
/**
利用内联函数求三角函数的面积
*/
#include<iostream>
#include<math.h>
using namespace std;
inline double area(double L,double W,double H)
{
double a=0.5*(L+W+H);
double s=sqrt(a*(a-L)*(a-W)*(a-H));
return s;
}
int main()
{
double x(3);//x=3
double y(4);
double z(5);
double NewArea;
NewArea=area(x,y,z);
cout<<"The area is:"<<NewArea<<endl;
return 0;
}
5.带默认参数的函数
(1)使用带默认参数的函数编程
#include<iostream>
using namespace std;
float area(float a=7,float b=8)
{
int z;
z=a*b;
return z;
}
int main()
{
float a,b,s1,s2,s3;
cout<<"Please input two numbers:";
cin>>a>>b;
s1=area();
s2=area(a);
s3=area(a,b);
cout<<"s1="<<s1<<endl;
cout<<"s2="<<s2<<endl;
cout<<"s3="<<s3<<endl;
return 0;
}
(2)声明时指定默认形参值的使用
#include<iostream>
using namespace std;
int main()
{
int add(int a=2,int b=3);//声明时赋值
int a,b;
int c1,c2;
cout<<"Please input two integer numbers:";
cin>>a>>b;
c1=add();
c2=add(a,b);
cout<<"c1="<<c1<<endl;
cout<<"c2="<<c2<<endl;
return 0;
}
int add(int a,int b)
{
int c;
c=a+b;
return c;
}
(3)默认形参值为全局变量和局部变量的使用
#include<iostream>
using namespace std;
int L,W,S;
void input(int a=2,int b=3)//定义函数,指定全局变量
{
L=a;
W=b;
}
void output()
{
S=L*W;
cout<<"The area is:"<<S<<endl;
}
void show()
{
void input(int a=5,int b=6);//声明函数,指定为局部默认形参值
input();
output();
}
int main()
{
input();
output();
input(8,6);
output();
show();
return 0;
}
啦啦啦啦