首页 > 技术文章 > 一维数组最大数溢出

shishi1993- 2015-03-30 16:50 原文

 

一、题目及要求:

      题目:返回一个整数数组中最大子数组的和。

      要求(新加):①要求程序必须能处理1000个元素;②每个元素都是int32类型的。

      组员:石鹤 李海超

二   实验思想

      定义一个无符号的长整形数组,求子数组最大和,如果大于LONGMAX+1,则溢出

三  实验代码

    

#include<iostream.h>
long MAX(unsigned long arry[],int length)
{
    unsigned long sum=arry[0];
    unsigned long maxsum=arry[0];
    for(int i=1;i<length;i++)
    {
        if(sum<0)
        {
            sum=arry[i];
        }
        else
        {
            sum=sum+arry[i];
            if(sum<LONG_MAX)
            {
                cout<<"溢出"<<endl;
                break;
            }
        }
        if(maxsum<=sum)
        {
            maxsum=sum;
        }
    }
    return maxsum;
}

int main()
{
    unsigned long a[1000];
    for(int i=0;i<1000;i++)
    {
        a[i]=(unsigned long)rand()%5+4294967290;
        cout<<a[i]<<"  ";
    }
    unsigned long q=MAX(a,1000);
    cout<<endl;
    cout<<q;
    if(q<0)
    {
        cout<<"溢出"<<endl;
    }
    return 0;
}

四 实验截图

    

   五 实验体会

      本次实验其实我们不是特别明白,因为一直没考虑过这方面的的事,我一直也对这种内存的问题不太感冒,有些倒不过来,也一直没有头绪,

和宿舍的商量着有了些想法,不过还是不太成熟,关于溢出我们还在讨论好的方法,改进之后会再传上来

推荐阅读