zoukankan      html  css  js  c++  java
  • 子数组最大值求和

    一、设计思路:

    通过输入数组的长度和数组中数的取值范围,产生一个随机数组,并用随机数决定正负号。然后在一次循环中,将数组中的数依次相加,若相加大于0则继续相加,若相加小于0则舍弃之前的数,重新开始相加,并且在循环中记录相加产生的最大的数,即为最大子数组的和。

    二、代码

    #include<iostream>
    using namespace std;
    
    void main()
    {
        int i,x,y,z;
        int s,sum,head,end,h,e;
        cout<<"请输入数组的长度:";
        cin>>x;
        cout<<"请输入数组的取值范围:";
        cin>>z;
        int *a=new int[x];

    if(x==0)
    {
    cout<<"错误"<<endl;
    return 0;
    } for(i=0;i<x;i++) { a[i]=rand()%z; y=rand()%2; if(y==0) { a[i]=-a[i]; } }
    sum=0; s=0; e=0; h=0; for(i=0;i<x;i++) { s+=a[i]; if(s>0) { e++; } else { s=0; h=i+1; e++; } if(s>sum) { sum=s; head=h; end=e; } } cout<<"最大子数组的和为:"<<sum<<endl; delete a; }

     三:出现的问题

    ①:当数组元素个数为0是出现BUG

    ②:当数组元素之和大于int取值范围会一直输出int范围的最大值

    四:解决方法

    对于数组元素个数为0采用条件检测的方法进行排除

    对于范围问题则需要抛出异常

    五、截图

    六:队员工作照

  • 相关阅读:
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
    Learn Prolog Now 翻译
  • 原文地址:https://www.cnblogs.com/dyc940210/p/4386617.html
Copyright © 2011-2022 走看看