posts - 137,comments - 0,views - 40595

一维数组:

复制代码
#include <iostream>
#include <windows.h>
#include <string>
using namespace std;
//在以下几种方法中,ages都不是真正的数组,实际上是一个指针 int *ages
int calAverage1(int ages[5]) {
    printf("%d\n",sizeof(ages));
    int s = 0;
    for (int i = 0; i < 5;i++) {
        s += ages[i];
    }
    return s / 5;
}
int calAverage2(int ages[],int n) {
    printf("%d\n", sizeof(ages));
    int s = 0;
    for (int i = 0; i < n; i++) {
        s += ages[i];
    }
    return s / 5;
}
int calAverage3(int *ages) {
    printf("%d\n", sizeof(ages));
    int s = 0;
    for (int i = 0; i < 5; i++) {
        s += ages[i];
    }
    return s / 5;
}
int calAverage4(int* ages,int n) {
    printf("%d\n", sizeof(ages));
    int s = 0;
    for (int i = 0; i < n; i++) {
        s += ages[i];
    }
    return s / 5;
}
int main() {
    int p[5] = {20,30,40,50,60}; 
    //计算平均年龄
    printf("%d\n", calAverage1(p));
    printf("%d\n", calAverage2(p,5));
    printf("%d\n", calAverage3(p));
    printf("%d\n", calAverage4(p,5));
    system("pause");
    return 0;
}
复制代码

二维数组:

复制代码
#include <iostream>
#include <stdio.h>
#include <windows.h>
#include <string>
using namespace std;
int calAverage1(int p[3][2]) {
    // 特别注意:此时 ages 不是真正的二维数组
    // 它实际上是一个指向一维数组的指针 int (*ages)[4]
    int s = 0;
    for (int i = 0; i < 3;i++){
        for (int j = 0; j < 2; j++) {
            s += p[i][j];
        }
    }
    return s / (3*2);
}
int calAverage2(int p[][2],int n) {
    int s = 0;
    for (int i = 0; i < n; i++) {
        for (int j = 0; j < 2; j++) {
            s += p[i][j];
        }
    }
    return s / (n * 2);
}
int calAverage3(int (*p)[2],int rows) {
    int s = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < 2; j++) {
            s += p[i][j]; 
        }
    }
    return s / (rows * 2);
}
int calAverage4(int *p, int rows,int rols) {
    int s = 0;
    for (int i = 0; i < rows; i++) {
        for (int j = 0; j < rols; j++) {
            s += (*(p+i*rols+ j)); //*(p+i*rols+ j)==》*(p[i*rols+j])
        }
    }
    return s / (rows * rols);
}
int main() {
    int ages[3][2] = {
                        20,35,
                        25,63,
                        78,25
    };
    
    printf("%d\n", calAverage1(ages));
    printf("%d\n", calAverage2(ages,3));
    printf("%d\n", calAverage3(ages, 3));
    printf("%d\n", calAverage4(*ages, 3,2));
    system("pause");
    return 0;
}
复制代码

posted on   wshidaboss  阅读(77)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· DeepSeek 开源周回顾「GitHub 热点速览」
· 记一次.NET内存居高不下排查解决与启示
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· .NET10 - 预览版1新功能体验(一)
< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5

点击右上角即可分享
微信分享提示