20250103-C12-函数
原题链接:33673.徐沐瑶专属笔记C++2025-01-03 11:41:53
发布于:江苏
一、自定义函数
1. 函数三步曲
function
功能,方法,函数
f(x) = 2*x+1
#include<iostream> //1.头文件
using namespace std; //2.命名空间:防止名称冲突
//(1)函数的声明 (可以省略)
//int xmw();
//void 表示无返回值
void xmw() //(2)定义函数
{
cout << "这是小码王函数 666";
}
//功能: 计算1~10的和
int f(int cnt){ //接收参数: 形式参数
int sum = 0;
for (int i=1; i<=cnt; i++){
sum += i;
}
return sum;
}
//3.主函数:程序的入口, 小绿旗
int main()
{
int n;
cin >> n;
cout << f(n); //传递参数 : 实际参数
// cout << 333 <<endl;
// //(3)函数的调用
// xmw();
return 0; //返回值
}
函数使用三步曲
(1)函数的声明;(2)函数的定义;(3)函数的调用
2. 函数应用实例:
实例1:返回三个数的最大值
#include<iostream>
using namespace std;
//(条件)?(1):(2) //三目运算符
int f(int a, int b, int c){
int t = (a>b?a:b);
return (t>c?t:c);
}
int main(){
int a, b, c;
cin >>a >> b >> c;
cout << f(a, b, c);
return 0;
}
实例2:回文数的判断
正反相同的数字, 如191,称为回文数.
实例3:A7850.完成素数判定函数
#include<iostream>
using namespace std;
bool prime(int n)
{
if (n<2) return 0;
for (int i=2; i<=n-1; i++)
if (n%i==0) return 0;
return 1;
}
int main(){
int n;
cin >> n;
if (prime(n)) cout<<"Yes";
else cout << "No";
return 0;
}
二、常用系统库函数(cmath)
cout << pow(2, 3) << endl; //幂函数
cout << abs(-6) << endl; //绝对值
cout << sqrt(64) << endl; //平方根
cout << floor(4.5) << endl; //向下取整
cout << ceil(4.5) << endl; //向上取整
cout << max(5, 3) << endl; //取较大值
cout << min(4, 3) << endl; //取较小值
这里空空如也
有帮助,赞一个