1. 程式人生 > >返回一個整數數組中最大子數組的和的程序

返回一個整數數組中最大子數組的和的程序

namespace sin 返回 h+ etc ios get 除法 clu

源程序:

#include<iostream>
#define n 100
using namespace std;
void main()
{
int a[n], b[n][n]; int length, i, j, w = 0, p = 0, q = 0, temp, m;
cout << "輸入隨機整數" << endl;
for (length = 0;;)
{
cin >> a[length];
length++;
if (getchar() == ‘\n‘)
{
break; } } cout << "這個數組的長度為:" << length << endl;
//求子數組
for (i = 0; i<length; i++)//兩次循環,進行排除法,判斷每個數所構成的最大子數組
{
m = i;
w = 0;
j = 0;
while (j <= length - 1)
{
w += a[m];
b[i][j] = w;
m++;
if (m>length - 1)
{
m = 0;
}
j++;
}
}

temp = b[0][0];
for (i = 0; i<length; i++)//將每個數對應的最大子數組進行判斷,最後得到整個整數組的最大子數組
{
for (j = 0; j<length; j++)
{
if (b[i][j]>temp)
{
temp = b[i][j];
p = i;
q = j;
}
}
}

cout << "最大子數組的值為:" << temp << endl;
cout << "最大子數組中元素的下標位子置:" << endl;
i = 0;
while (i <= q)
{
cout << p << " ";
p++;
if (p >= length)
{
p = 0;
}
i++;
}

cout << endl;
}

返回一個整數數組中最大子數組的和的程序