子数组返回一个整数数组中最大的和

本次实验的要求:

1要求程序必须能处理1000个程序;

2每个元素是int32类型的,出现子数组之和大于整型表示的最大范围会是什么情况;

3输入一个整形数组,数组里有正数也有负数。

4数组中连续的一个或多个整数组成一个子数组,每个子数组都有一个和。

5求所有子数组的和的最大值。要求时间复杂度为O(o)。

设计思路:

将数组的大小定义为1000,每个元素定义为int32类型,取数值时对数成2的32次方,这样数值可以越界。

程序代码

 
 #include <iostream>
  #include<stdlib.h>
  #include<time.h>
  using namespace std;
  
  int main()
  {
     int i;
     int a[1000];
     int max = 0;
     int b = 0;
 
     srand(time(NULL));
     cout<<"数组为:"<<endl;
     for (i = 0; i<1000; i++)
    {
         a[i] = rand()*4294967296;
     }
   for (i = 0; i<1000; i++)
   {
       cout << a[i] << '\t';
    }
    cout << endl;
 
   for (i = 0; i < 1000; i++)
    {
       b += a[i];
        if (b < 0)
            b = 0;
        if (b > max)
            max = b;
    }
     if (max == 0)
    {
         max = a[0];
        for (i = 0; i < 1000; i++)
        {
             if (max < a[i])
           {
                 max = a[i];
             }
         }    
     }
     cout <<"最大子数组为:"<< max << endl;
     system("pause");
     return 0;
 }
运行结果
1有溢出时

2出结果时

实验总结

   通过运行调试,了解了时间复杂度的重要性,当程序有溢出时,运行结果会都变成0,而且运行时一定要记得先把符号成对的打出来,要不然很容易检查不出错误代码。

小组成员图片

 

 

 

 

 

 

 

 
posted @ 2018-10-14 17:06  唯心123  阅读(180)  评论(0编辑  收藏  举报