软件工程第三次作业
一.问题描述
题目(1):最大连续子数组和(最大子段和)
给定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。
二.程序设计
代码地址:https://github.com/codelover728/-/tree/master
#include<stdio.h>
#include<stdlib.h>
#define MAX 100
int maxsz(int *a,int L, int R);
//int a[MAX];
int main()
{
int i, count;
scanf_s("%d", &count);
for (i = 0; i < count; i++)
scanf_s("%d", &a[i]);
printf("%d\n", maxsz(0, count - 1));
system("pause");
return 0;
}
int maxsz(int *a,int L, int R)
{
int center, i, sum, L_sum, R_sum, L_max, R_max;
if (L == -1|| R==1)
return 0;
center = (L + R) >> 1;
if (L == R)
return a[L] > 0 ? a[L] : 0;
else
{
L_sum = maxsz(a,L, center);
R_sum = maxsz(a,center + 1, R);
sum = 0;
L_max = 0;
for (i = center; i >= L; i--)
{
sum += a[i];
if (sum > L_max)
L_max = sum;
}
sum = 0;
R_max = 0;
for (i = center + 1; i <= R; i++)
{
sum += a[i];
if (sum > R_max)
R_max = sum;
}
sum = R_max + L_max;
if (sum < L_sum)
sum = L_sum;
if (sum < R_sum)
sum = R_sum;
}
return sum;
}
三.流程图
四.测试代码
采用判定条件覆盖,即使判断的每个条件的可能取值至少执行一次。
序号 | 条件 | 样例 |
---|---|---|
1 | len==NULL | n=-5 : 11,-32,3,-4,-5 |
2 | n>0 | n=7 : 1,-4,3,10,-4,7,2 |
3 | sum<len[i] | n=6 :-2,11,-4,13,-5,-2 |
4 | sum></len[i]>len[i] | n=6 :2,11,-4,13,-5,-2 |
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1) //len==NULL||n<0
{
int len[] = { 11,-32,3,-4,-5 };
int n = -5;
int k;
k = getMAX(len, n);
Assert::AreEqual(k, 0);
}
TEST_METHOD(TestMethod2) // sum<len[i]
{
int len[] = { -2,11,-4,13,-5,-2 };
int n = 6;
int k;
k = getMAX(len, n);
Assert::AreEqual(k, 20);
}
TEST_METHOD(TestMethod3) //sum>len[i]
{
int len[] = {2,11,-4,13,-5,-2 };
int n =6;
int k;
k = getMAX(len, n);
Assert::AreEqual(k,22);
}
TEST_METHOD(TestMethod4)
{
int len[] = { 1,-4,3,10,-4,7,2 };
int n= 7;
int k;
k = getMAX(len, n);
Assert::AreEqual(k, 18);
}
};
}
五.单元测试结果
六.归纳与总结
通过本次作业,我更加熟悉了单元测试的使用,同时也让我知道了如何更好地去进行程序测试。