布伦塔诺

软件工程第三次作业

题目选择

  本次作业我选择的是题目(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。
-- 引用自《百度百科》

代码程序

  此次编程我采用的是C++,代码已提交至GitHub,代码地址:https://github.com/FirstEye/lkk.git
  标头.h:

class ArrayMaxSum
{
private:
	int* array_;
	int number;
public:
	ArrayMaxSum();
	ArrayMaxSum(int* a, int n);
	~ArrayMaxSum();
	int getArrayMaxSum();
};

  源1.cpp:

#include<iostream>
#include"标头.h"
using namespace std;

ArrayMaxSum::ArrayMaxSum()
{
	cin >> number;
	if (number > 0)
	{
		array_ = new int[10];
		for (int i = 0; i < number; i++)
		{
			cin >> *(array_ + i);
		}
	}
	else
	{
		number = 0;
		array_ = NULL;
	}
}
ArrayMaxSum::ArrayMaxSum(int* a, int n)
{
	array_ = new int[10];
	for (int i = 0; i < n; i++)
	{
		array_[i] = a[i];
	}
	number = n;
}
ArrayMaxSum::~ArrayMaxSum()
{
	delete[]array_;
	array_ = NULL;
}
int ArrayMaxSum::getArrayMaxSum()
{
	if (array_ == NULL)return 0;
	int tempsum = array_[0];
	int maxsum = tempsum>0?tempsum:0;
	for (int i = 1; i < number; i++)
	{
		tempsum = tempsum + array_[i] > array_[i] ? tempsum + array_[i] : array_[i];
		maxsum = tempsum > maxsum ? tempsum : maxsum;
	}
	return maxsum;
}

  源.cpp:

#include<iostream>
#include"标头.h"
using namespace std;

int main()
{
	int a[] = { -2,11,-4,-8,13,-5,-2 };
	ArrayMaxSum ams1 = ArrayMaxSum(a, 7);
	cout << ams1.getArrayMaxSum() << endl;
	ArrayMaxSum ams2 = ArrayMaxSum();
	cout << ams2.getArrayMaxSum() << endl;
	system("pause");
	return 0;
}

  程序运行结果:

测试部分

  本次测试我采用的是判定/条件覆盖,流程图如下:

  样例选择:

    样例1:{};
    样例2:{-2,11,-4,-8,13,-5,-2}

测试代码:

#include "stdafx.h"
#include "CppUnitTest.h"
#include "../Project1/标头.h"

using namespace Microsoft::VisualStudio::CppUnitTestFramework;

namespace UnitTest1
{		
	TEST_CLASS(UnitTest1)
	{
	public:
		
		TEST_METHOD(TestMethod1)
		{
			// TODO: 在此输入测试代码
			int a[] = { -2,11,-4,-8,13,-5,-2 };
			ArrayMaxSum asm2 = ArrayMaxSum(a, 7);
			Assert::AreEqual(13, asm2.getArrayMaxSum());
		}
		TEST_METHOD(TestMethod2)
		{
			// TODO: 在此输入测试代码
			int* a = {};
			ArrayMaxSum asm2 = ArrayMaxSum(a, 0);
			Assert::AreEqual(0, asm2.getArrayMaxSum());
		}
	};
}

测试结果:

posted on 2019-04-16 13:53  布伦塔诺  阅读(217)  评论(0编辑  收藏  举报

导航