返回整數數組最大子數組
阿新 • • 發佈:2018-10-14
.com 組成 長度 。。 use 感想 rand() ima null
#include<stdlib.h>
#include<time.h>
using namespace std; int main()
{
int i;
int a[10000];
int max = 0;
int b = 0; srand(time(NULL));
cout<<"數組為:"<<endl;
for (i = 0; i<10000; i++)
{
a[i] = rand()*4294967296 ;
}
for (i = 0; i<10000; i++)
{
cout << a[i] << ‘\t‘;
}
cout << endl; for (i = 0; i < 10000; i++)
{
b += a[i];
if (b < 0)
b = 0;
if (b > max)
max = b;
}
if (max == 0)
{
max = a[0];
for (i = 0; i < 10000; i++)
{
if (max < a[i])
{
max = a[i];
}
}
}
cout <<"最大子數組為:"<< max << endl;
system("pause");
return 0;
} 截圖:
感想:
有的時候程序運行結果會是都是0,這好像是因為數據過多導致程序出錯,數據長度減少就可以解決了。程序比較難,需要多加考慮。
附上和李子木同學的合照。。
應王老師要求,和李子木同學共同完成編程任務。
要求程序必須能處理1000 個元素,每個元素是int32 類型的;輸入一個整形數組,數組裏有正數也有負數。
數組中連續的一個或多個整數組成一個子數組,每個子數組都有一個和。 求所有子數組的和的最大值。要求時間復雜度為O(n)。 #include <iostream>#include<stdlib.h>
#include<time.h>
using namespace std; int main()
{
int i;
int a[10000];
int max = 0;
int b = 0; srand(time(NULL));
cout<<"數組為:"<<endl;
for (i = 0; i<10000; i++)
{
a[i] = rand()*4294967296 ;
}
for (i = 0; i<10000; i++)
{
cout << a[i] << ‘\t‘;
}
cout << endl; for (i = 0; i < 10000; i++)
{
b += a[i];
if (b < 0)
b = 0;
if (b > max)
max = b;
}
if (max == 0)
{
max = a[0];
for (i = 0; i < 10000; i++)
{
if (max < a[i])
{
max = a[i];
}
}
}
cout <<"最大子數組為:"<< max << endl;
system("pause");
return 0;
} 截圖:
返回整數數組最大子數組