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。
-- 引用自《百度百科》
程序代码:
`#include <stdio.h>
include <stdlib.h>
include <math.h>
include
using namespace std;
int main()
{
int number[50];
int n, i, j, k;
int sum = 0;
int max = 0;
cin >> n;
for (i = 0; i < n; i++)
{
cin >> number[i];
}
for (int i = 0; i < n; i++)
{
for (int j = i; j < n; j++)
{
int sum = 0;
for (int k = i; k <= j; k++)
{
sum += number[k];
}
if (sum > max)
{
max = sum;
}
}
}
cout << max;
return 0;
}
`
3.代码流程图
4.我选用判定条件覆盖,使用五组测试用例
num[] = { 0 };
num[4] = { -2,-2,-3,-4 };
num[4] = { 4,2,6,5,};
num[4] = { 5,-2,3,4 };
num[4] = { 3,-8,6,4 };
测试代码如下:
TEST_METHOD(TestMethod1)
{
int max, num[] = { 0 };
max = test(num, 0);
Assert::AreEqual(max, 0);
}
TEST_METHOD(TestMethod2)
{
int max, num[4] = { -2,-2,-3,-4 };
max = test(num, 4);
Assert::AreEqual(max, 0);
}
TEST_METHOD(TestMethod3)
{
int max, num[4] = { 4,2,6,5,};
max = test(num, 4);
Assert::AreEqual(max, 17);
}
TEST_METHOD(TestMethod4)
{
int max, num[4] = { 5,-2,3,4 };
max = test(num, 4);
Assert::AreEqual(max, 10);
}
TEST_METHOD(TestMethod5)
{
int max, num[4] = { 3,-8,6,4 };
max = test(num, 4);
Assert::AreEqual(max, 10);
}
测试结果如下所示:{{uploading-image-877812.png(uploading...)}}