菜单 学习猿地 - LMONKEY

VIP

开通学习猿地VIP

尊享10项VIP特权 持续新增

知识通关挑战

打卡带练!告别无效练习

接私单赚外块

VIP优先接,累计金额超百万

学习猿地私房课免费学

大厂实战课仅对VIP开放

你的一对一导师

每月可免费咨询大牛30次

领取更多软件工程师实用特权

入驻
319
0

C++基础学习-函数

原创
05/13 14:22
阅读数 85582

image
image
image
image
image

#include <iostream>
using namespace std;
#include <string>//用C++风格字符串时候,要包含这个头文件
#include<ctime>//time系统时间头文件包含



//函数定义
int add(int num1,int num2)//定义中的num1 , num2称为形式参数,简称形参
{
    int sum = num1 + num2;
    return sum;
}
int main() 
{
    int a = 10; 
    int b = 10;
    //调用add函数
    int sum = add(a, b);//调用时的a,b称为实际参数,简称实参
    cout << "sum = " << sum << endl;
    a = 100;
    b = 100;
    sum = add(a, b);
    cout << "sum = " << sum << endl;
    
    system("pause");
}

image
image
image

#include <iostream>
using namespace std;
#include <string>//用C++风格字符串时候,要包含这个头文件
#include<ctime>//time系统时间头文件包含

//函数定义
//定义函数,实现两个数字进行交换函数
void swap(int num1,int num2)//定义中的num1 , num2称为形式参数,简称形参
{
    cout << "交换前:" << endl;
    cout << "num1=" << num1 << endl;
    cout << "num2=" << num2 << endl;
    int temp = num1;
    num1 = num2;
    num2 = temp;
    cout << "交换后:" << endl;
    cout << "num1=" << num1 << endl;
    cout << "num2=" << num2 << endl;

}
int main() 
{
    int a = 20; 
    int b = 10;
    //调用add函数
    swap(a, b);//调用时的a,b称为实际参数,简称实参
    
    system("pause");
}

image
image
image

#include <iostream>
using namespace std;
#include <string>//用C++风格字符串时候,要包含这个头文件
#include<ctime>//time系统时间头文件包含

//函数常见样式
// 1、无参无返
void test01()
{
    cout << "this is test0l " <<endl;
}

// 2、有参无返
void test02(int a)
{
    cout << "this is test02 a= " << a << endl;
}

// 3、无参有返
int test03()
{
    cout << "this is test03 " << endl;
    return 1000;
}

// 4、有参有返
int test04(int a)
{
    cout << "this is test04 " << endl;
    return a;
}

int main() 
{
    //无参无返函数调用
    test01();
    // 2、有参无返
    test02(100);
    // 3、无参有返
    int num1 = test03();
    cout << "num1= " << num1 << endl;
    // 4、有参有返
    int num2 = test04(10000);
    cout << "num2= " << num2 << endl;
    
    system("pause");
}

image
image

#include <iostream>
using namespace std;
#include <string>//用C++风格字符串时候,要包含这个头文件
#include<ctime>//time系统时间头文件包含

// 函数的声明
int max(int a, int b);

//比较函数,实现两个整型数字进行比较,返回较大的值
//定义
int max(int a, int b)
{
    return a > b ? a : b;
}
        
int main() 
{
    int a = 10;
    int b = 20;
    cout << max(a, b) << endl;
    
    system("pause");
}

image
image
image
image
image
image

发表评论

0/200
319 点赞
0 评论
收藏