软件工程(2019)第三次个人作业
一.题目要求
- 题目:最大连续子数组和(最大子段和)
- 问题: 给定n个整数(可能为负数)组成的序列a[1],a[2],a[3],…,a[n],求该序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。当所给的整数均为负数时定义子段和为0,依此定义,所求的最优值为: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
- 例如,当(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)时,最大子段和为20。
-- 引用自 百度百科
二.流程图
三.代码
#include <iostream>
using namespace std;
int maxarray(int *arr, int length)
{
int sum = 0, max = 0, i = 0;
for (i = 0; i < length; i++)
{
sum = sum + arr[i];
if (sum < arr[i])
sum = arr[i];
if (sum > max)
max = sum;
}
return max;
}
int main ()
{
int i, length;
int arr[100];
cin >> length;
for (i = 0;i < length;i++)
cin >> arr[i];
int max = maxarray(arr, length);
cout << max;
system("pause");
}
- 程序运行结果:
四.测试
- 此次测试我使用的是判定/条件覆盖,四组测试数据分别为:
- arrary[]={} max=0;
- array[] = { -2,11,-4,13,-5,-2 } max=20;
- array[] = { -1,-3,-5,-7 } max=0;
- array[] = { 1,3,5,7 } max=16.
-
测试代码:
TEST_METHOD(TestMethod1) { int *array = {}; int length = 0; int max=maxarray(array, length); Assert::AreEqual(max, 0); } TEST_METHOD(TestMethod2) { int array[] = { -2,11,-4,13,-5,-2 }; int length = sizeof(array) / sizeof(int); int max=maxarray(array, length); Assert::AreEqual(max, 20); } TEST_METHOD(TestMethod3) { int array[] = { -1,-3,-5,-7 }; int length = sizeof(array) / sizeof(int); int max = maxarray(array, length); Assert::AreEqual(max, 0); } TEST_METHOD(TestMethod4) { int array[] = { 1,3,5,7 }; int length = sizeof(array) / sizeof(int); int max = maxarray(array, length); Assert::AreEqual(max, 16); }
-
测试结果: