一维数组:
#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; }标签:return,int,ages,C++,参数传递,++,数组,printf,include From: https://www.cnblogs.com/smartlearn/p/16817967.html