c++第一节

本文介绍了C++编程中的实习任务,包括命名空间的使用、函数重载以及如何实现数组元素逆序和获取数组最大值的函数。
摘要由CSDN通过智能技术生成

实习任务一

1.3.1命名空间

(1)namespace xxx {
    double fun(double a, double b) {

        return a + b;
    }
}

namespace yyy {
    double fun(double a, double b) {

        return (a + b) / 2;
    }
}
#include <iostream>
using namespace std;
using namespace yyy;

int main() {
    cout << fun(1, 4) << endl;
    using xxx::fun;
    cout << fun(1, 4) << endl;
    cout << yyy::fun(1, 4) << endl;
    return 0;
}

(2)重载特性 自动以形式参数选择函数

#include <iostream>
#include <string>
using namespace std;

string add(const string &s1, const string &s2) {
    return s1 + s2;
}

double add(double a, double b) {
    return a + b;
}

int main() {
    cout << add("hello", "world") << endl;
    cout << add(3, 5) << endl;
    cout << add('3', '5') << endl;
    return 0;
}

(3)

#include <iostream>
using namespace std;

int gcd(int m, int n) {
    if (n == 0)
        return m;
    return gcd(n, m % n);
}

int main() {

    cout << "1:" << gcd(20, 8) << endl;
    cout << "2:" << gcd(36, 64) << endl;
    return 0;
}

1.3.2实习任务二:

1) 编写函数 reverse ,将数组中的元素逆序,函数原型如下。
void reverse( int array[], int size );
其中 array 为指向数组的指针, size 表示数组的大小。
void reverse(int array[], int size) {
    int temple;
    for (int i = 0; i < size / 2; i++) {
        temple = array[size - i - 1];
        array[size - i - 1] = array[i];
        array[i] = temple;
    }
}
2) 编写函数 getMax ,计算数组的最大值,函数原型如下。
int getMax(int *array, int size); 8
其中 array 为指向数组的指针, size 表示数组的大小。

#include <iostream>
using namespace std;

int getMax(int *array, int size) {
    int i = 0;
    int f = *array;
    for (i = 0; i < size; i++) {
        if (f < * (array + i))
            f = *(array + i);
    }
    return f;
}

int main() {
    int size = 5;
    int a[5] = {1, 2, 3, 4, 5};
    int *array;
    array = a;
    cout << getMax(array, size);

    return 0;
}

  • 9
    点赞
  • 20
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值