软件工程第三次作业
一、题目要求
问题:
给定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://git.dev.tencent.com/TianyiZhang/software-engineering.git
#include<stdio.h>
#include<stdlib.h>
int MaxSubseqSum4(int a[], int n)
{
int i = 0;
int thisSum = 0, sum = 0;
for (i = 0; i < n; i++) {
thisSum += a[i];
if (thisSum > sum) {
sum = thisSum;
}
else if (thisSum <= 0) {
thisSum = 0;
}
}
return sum;
}
int main()
{
int a[1000], n, i,m;
scanf_s("%d", &n);
for (i = 0; i < n; i++)
{
scanf_s("%d", &a[i]);
}
m=MaxSubseqSum4(a, n);
printf("%d", m);
system("pause");
return 0;
}
三、代码流程图
四、测试代码
· 测试结果情况:
1、输入整数n<0.
2、整数元素均为负数.
3、整数元素均为正数.
4、最大子段和在后.
5、最大子段和在前.
#include "stdafx.h"
#include "CppUnitTest.h"
#include"../软工第三次作业/标头.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
int a[] = { 0 };
int n = -1;
Assert::AreEqual(MaxSubseqSum4(a, n), 0);
}
TEST_METHOD(TestMethod2)
{
int a[] = { -1,-2,-3,-4. - 5 };
int n = 5;
Assert::AreEqual(MaxSubseqSum4(a, n), 0);
}
TEST_METHOD(TestMethod3)
{
int a[] = { 1,2,3,4,5 };
int n = 5;
Assert::AreEqual(MaxSubseqSum4(a, n), 15);
}
TEST_METHOD(TestMethod4)
{
int a[] = { 4,5,-6,-7,10 };
int n = 5;
Assert::AreEqual(MaxSubseqSum4(a,n), 10);
}
TEST_METHOD(TestMethod5)
{
int a[] = { 4,5,-6,-7,8 };
int n = 5;
Assert::AreEqual(MaxSubseqSum4(a, n), 9);
}
};
}
五、单元测试结果