返回一個整數數組中最大子數組的值(程序能處理1000個元素)
阿新 • • 發佈:2018-10-14
src mes () 最大子數組 一個 int32 圖片 http 課堂
課堂練習:
題目:要求返回一個整數數組中最大子數組的值
要求:程序必須能處理1000個元素
每個元素是int32類型的
設計思路:
將數組的大小定義為1000,每個元素定義為int32類型,取數值時對數成2的32次方,這樣數值可以越界。 程序: #include <iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
int i;
int a[1000];
int max = 0;
int b = 0;
srand(time(NULL));
cout<<"數組為:"<<endl;
for (i = 0; i<1000; i++)
{
a[i] = rand();
}
for (i = 0; i<1000; i++)
{
cout << a[i] << ‘\t‘;
}
cout << endl;
for (i = 0; i < 1000; i++)
{
b += a[i];
if (b < 0)
b = 0;
if (b > max)
max = b;
}
if (max == 0)
{
max = a[0];
for (i = 0; i < 1000; i++)
{
if (max < a[i])
{
max = a[i];
}
}
}
cout <<"最大子數組為:"<< max << endl;
system("pause");
return 0;
} 運行結果:
將數組的大小定義為1000,每個元素定義為int32類型,取數值時對數成2的32次方,這樣數值可以越界。 程序: #include <iostream>
#include<stdlib.h>
#include<time.h>
using namespace std;
int main()
{
int i;
int a[1000];
int max = 0;
int b = 0;
srand(time(NULL));
cout<<"數組為:"<<endl;
for (i = 0; i<1000; i++)
{
a[i] = rand();
}
for (i = 0; i<1000; i++)
{
cout << a[i] << ‘\t‘;
}
cout << endl;
for (i = 0; i < 1000; i++)
{
b += a[i];
if (b < 0)
b = 0;
if (b > max)
max = b;
}
if (max == 0)
{
max = a[0];
for (i = 0; i < 1000; i++)
{
if (max < a[i])
{
max = a[i];
}
}
}
cout <<"最大子數組為:"<< max << endl;
system("pause");
return 0;
} 運行結果:
合影:
返回一個整數數組中最大子數組的值(程序能處理1000個元素)