C风格的C++代码这么写
程序代码:
#include <cstdio>
const size_t N = 2;
int sum_diagonal( const int s[N][N] )
{
int sum = 0;
for( size_t i=0; i!=N; ++i )
sum += s[i][i];
return sum;
}
int main()
{
int s[N][N];
for( size_t i=0; i!=N; ++i )
for( size_t j=0; j!=N; ++j )
scanf( "%d", &s[i][j] );
int sum = sum_diagonal( s );
printf( "%d", sum );
return 0;
}
或许有人会将二维数组当成一维数组来处理,这样通用性提高,如下
程序代码:
#include <cstdio>
int sum_diagonal( const int* s, size_t n )
{
int sum = 0;
for( size_t i=0; i!=n; ++i )
sum += s[i*n+i];
return sum;
}
int main()
{
const size_t N = 2;
int s[N][N];
for( size_t i=0; i!=N; ++i )
for( size_t j=0; j!=N; ++j )
scanf( "%d", &s[i][j] );
int sum = sum_diagonal( &s[0][0], N );
printf( "%d", sum );
return 0;
}
但这一行为在C标准中找不到依据,你可以这么做,但尽量别这么做
C++可以用模板来处理这一点
程序代码:
#include <iostream>
template<typename T, size_t N>
T sum_diagonal( const T (&s)[N][N] )
{
T sum = 0;
for( size_t i=0; i!=N; ++i )
sum += s[i][i];
return sum;
}
using namespace std;
int main()
{
int s[2][2];
for( size_t i=0; i!=sizeof(s)/sizeof(s[0]); ++i )
for( size_t j=0; j!=sizeof(s[0])/sizeof(s[0][0]); ++j )
cin >> s[i][j];
int sum = sum_diagonal( s );
cout << sum << endl;
return 0;
}