一、设计思路
1.数组叠加凑成循环,再套用以前求最大值的代码实现。
二、源代码
#include<iostream.h> #include<stdlib.h> #include<time.h> int main() { cout<<"---------------------求数组中子数组和的最大值的小程序----------------------"<<endl; cout<<endl; int a[5]; int c[5]; int b[10]; int i; srand( (unsigned)time( NULL ) );//随机数种子为当前计算机时间。 for(i=0;i<5;i++) { a[i]=rand()%22-11;//得到一组-10到10的整数; cout<<a[i]<<" "; } cout<<endl; for(i=0;i<9;i++) { if(i<5) b[i]=a[i]; else b[i]=a[i-5]; //cout<<b[i]<<" "; } cout<<endl; //最大值求法 int sum=0; int GreateSum=0; //1-5 for ( i=0;i<5;i++) { sum+=b[i]; if (sum<0) { sum=0; } if (sum>GreateSum) { GreateSum=sum; } } if (GreateSum==0) { for (int i=0;i<5;i++) { if (GreateSum==0) { GreateSum=b[i]; } else if (GreateSum<b[i]) { GreateSum=b[i]; } } } c[0]=GreateSum; //2-6 sum=0; GreateSum=0; for ( i=1;i<6;i++) { sum+=b[i]; if (sum<0) { sum=0; } if (sum>GreateSum) { GreateSum=sum; } } if (GreateSum==0) { for (int i=1;i<6;i++) { if (GreateSum==0) { GreateSum=b[i]; } else if (GreateSum<b[i]) { GreateSum=b[i]; } } } c[1]=GreateSum; //3-7 sum=0; GreateSum=0; for ( i=2;i<7;i++) { sum+=b[i]; if (sum<0) { sum=0; } if (sum>GreateSum) { GreateSum=sum; } } if (GreateSum==0) { for (int i=2;i<7;i++) { if (GreateSum==0) { GreateSum=b[i]; } else if (GreateSum<b[i]) { GreateSum=b[i]; } } } c[2]=GreateSum; //4-8 sum=0; GreateSum=0; for ( i=3;i<8;i++) { sum+=b[i]; if (sum<0) { sum=0; } if (sum>GreateSum) { GreateSum=sum; } } if (GreateSum==0) { for (int i=3;i<8;i++) { if (GreateSum==0) { GreateSum=b[i]; } else if (GreateSum<b[i]) { GreateSum=b[i]; } } } c[3]=GreateSum; //5-9 sum=0; GreateSum=0; for ( i=4;i<9;i++) { sum+=b[i]; if (sum<0) { sum=0; } if (sum>GreateSum) { GreateSum=sum; } } if (GreateSum==0) { for (int i=4;i<9;i++) { if (GreateSum==0) { GreateSum=b[i]; } else if (GreateSum<b[i]) { GreateSum=b[i]; } } } c[4]=GreateSum; for(i=0;i<5;i++) { //cout<<c[i]<<" "; if(GreateSum<c[i]) { GreateSum=c[i]; } } cout<<endl; cout<<"最大子数组和的值为:"<<GreateSum<<endl; return 0; }
三、运行截图
四、心得体会
套用以前代码感觉省事,因为许多变量都注释,结构也清晰。主要是子数组位置尚未实现,有待修改。其次写完感觉程序有缺陷,扩展性不好,数组范围有限制。