结对开发Ⅳ——一维数组求和最大的子数组(大数溢出)

一、设计思路

  由于我们第一个版本的算法不太好,导致后来拓展的两个程序无法很好地实现,我们就又重新设计了一个。我们是先写的首尾相连的那个程序,在它的基础上稍微修改了一下。

(1)数据结构是链表,存放数据和next指针;

(2)生成特别大的随机数,数据也设置得比较多。

二、源代码

 1 // 最大子数组的和溢出.cpp : Defines the entry point for the console application.
 2 // 袁佩佩 于海洋
 3 
 4 #include "stdafx.h"
 5 #include<iostream.h>
 6 #include "stdlib.h"
 7 #include<time.h>
 8 #define NUM 1000
 9 
10 /*链表数据结构*/
11 typedef struct LNode
12 {
13     int data;
14     struct LNode *next;
15 }LNode,*LinkList;
16 /*链表的初始化*/
17 void InitList(LinkList &L)
18 {
19     L=new LNode;
20     L->next=NULL;
21 }
22 /*链表数据的插入*/
23 void InsertList(LinkList &L)
24 {
25     LNode *head,*temp;
26     head=L;
27     srand(time(NULL));
28     for(int i=0;i<NUM;i++)
29     {
30         temp=new LNode;
31         temp->data=rand()%2000000000-10000;
32         temp->next=NULL;
33         head->next=temp;
34         head=head->next;
35     }
36 }
37 void output(LinkList L)
38 {
39     for(int i=0;i<NUM;i++)
40     {
41         cout<<L->next->data<<" ";
42         L=L->next;
43         if((i+1)%10==0)
44         {
45             cout<<endl;
46         }
47     }
48 }
49 int main(int argc, char* argv[])
50 {
51     int max,sum,flag=0;                //sum是子数组的和,max是最大的子数组的和
52     int ordern=0,orderx=0;
53     LinkList L;
54     LNode *temp1,*temp2;
55     InitList(L);
56     InsertList(L);                    //由用户往链表中插入数据
57     temp2=L->next;
58     max=L->next->data;                //max初值是链表中第一个数
59     for(int j=0;j<NUM;j++,temp2=temp2->next)
60     {
61         for(int k=j;k<NUM;k++)
62         {
63             sum=0;
64             temp1=temp2;
65             for(int h=j;h<=k;h++,temp1=temp1->next)
66             {
67                  sum=sum+temp1->data;
68             }
69              if(max<sum)             //将最大值赋给max,并且保存当时的序号 
70              {
71                  max=sum;
72                  ordern=j;
73                  orderx=k;
74              }
75         }
76     }
77     if(sum==2147483647)
78     {
79         cout<<"数据溢出,程序出错!!!";
80     }
81     temp1=L->next;
82     cout<<"数组:"<<endl;
83     output(L);
84     cout<<endl<<"最大子数组是:";
85     for(int i=0;i<ordern;i++)         //找出取得最大值的时候的子数组的第一个数
86     {
87         temp1=temp1->next;
88     }
89     for(j=0;j<(orderx-ordern+1);j++,temp1=temp1->next)//将取得最大和的子数组元素输出
90     {
91         cout<<temp1->data<<"  ";
92     }
93     cout<<endl<<"最大子数组的和是:"<<max<<endl;;
94 
95     return 0;
96 }

 

三、运行截图

当代码中产生随机数的范围过大,编译器提示

 

 

四、心得体会

  虽然这次的题目要求看起来没什么难度,但是事实证明与计算机底层相接的部分才是难点啊。用软件解决硬件问题让我们头疼了很久,我们曾经有两次以为自己调出来了,但是继续把数值增大后,结果就不正确了。我们就另外写了个小程序来观察int32 类型的边界值有多大,然后我们发现最大值是232-1,再加一,就会变成-232我们就设置了相应的判断条件,使最大值溢出时提示出错。

 

五、无图无真相

posted @ 2015-03-28 23:20  JJJanepp  阅读(230)  评论(2编辑  收藏  举报