您的位置:首页 > 编程语言

编程题 矩阵一周元素之和与单词颠倒位置输出

2015-10-11 15:08 323 查看
矩阵一周元素之和与单词颠倒位置输出

1、M*N数组外围数组之和

如3*3数组:

1  2  3

4  5  6

7  8  9

和为1+2+3+6+9+8+7+4=40

函数原型为: int fun(int *a,int m,int n);

这里要注意int *a其中a是一个一维数组。不能直接当二维数组应用。

int fun(int *a,int M,int N)
{
int i,sum=0;
for(i=0;i<N;i++)   //第一行元素与最后一行的元素之和
sum+=a[i]+a[(M-1)*N+i];

for(i=1;i<M-1;i++)   //其余各行第一个元素与最后一个元素之和
sum+=a[i*N]+a[i*N+N-1];
return sum;
}


main()函数调用:

int a[12]={1,2,3,4,5,6,7,8,9,10,11,12};

int n=fun(a,4,3)

当然也可以先把一维数组转出二位数组:

int **b;
b=new int *[M];
for(int i=0;i<M;i++)
     b[i]=new int
;

for(int i=0;i<M;i++)
      for(int j=0;j<N;j++)
            b[i][j]=a[i*N+j];

       用完记得释放,即:

for(int i=0;i<M;i++)
     delete b[i];
delete b;

2、单词颠倒输出:

如输入:I am programmer

输出为:programmer am I

C++ code

char *fun(char *sstr,char *dstr)
{
char *t;
char *p;
int len=strlen(sstr);
p=new char[len+1];
t=new char[len+1];

for(int i=0;i<len;i++)
t[i]=sstr[i];   //方便修改数组中的内容
t[len]='\0';
for(int i=0;i<len;i++)  //必须的
p[i]='\0';

while(len--)
{
if(*(t+len)==' ')
{
p=strcat(p,t+len+1);
*(p+strlen(p))=' ';
*(p+strlen(p)+1)='\0';
t[len]='\0';
}
}

//处理第一个单词
p=strcat(p,t);
//cout<<p<<endl;
strcpy(dstr,p);
delete [] p;
delete [] t;
return dstr;
}


java code 很简单

import java.util.Scanner;;
public class Main
{
public static void main(String args[])
{
Scanner in=new Scanner(System.in);
String str=null;
str=in.nextLine();
String st[]=str.split(" ");

for(int i=st.length-1;i>=0;i--)
{
System.out.print(st[i]);
System.out.print(" ");
}
}
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  c++语言