代码如下:
include <stdio.h>
include <stdlib.h>
int main()
{
int* arr;
int N = 0, input = 0, i = 0;
int sum = 0, max = 0;
scanf_s("%d", &N);
arr = (int*)malloc(sizeof(int) * N);
int minus = 0;
//对数组进行赋初值,并且记录负数个数
for (i = 0; i < N; i++)
{
scanf_s("%d", &input);
arr[i] = input;
if (input < 0)
{
minus++;
}
}
//如果全为负数,直接输出0,并结束程序
if (minus == N)
{
printf("0");
return 0;
}
//对最大子数组进行求解
max = arr[1];
for (i = 0; i < N; i++)
{
sum = sum + arr[i];
if (sum > max)
{
max = sum;
}
if (sum < 0)
{
sum = 0;
}
}
printf("%d", max);
return 0;
}
测试代码如下:
include "stdafx.h"
include "CppUnitTest.h"
include "..\Max\标头.h"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
int arr[6] = { -2,11,-4,13,-5,-2 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 20);
}
TEST_METHOD(TestMethod2)
{
int arr[5] = { -1,2,3,-6,7 }, max;
max = Max(arr, 5);
Assert::AreEqual(max, 7);
}
TEST_METHOD(TestMethod3)
{
int arr[6] = { -2,-11,-4,-13,-5,-2 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 0);
}
TEST_METHOD(TestMethod4)
{
int arr[6] = { 1,2,3,4,5,6 }, max;
max = Max(arr, 6);
Assert::AreEqual(max, 21);
}
};
}
四、总结:
通过这次实验,我了解判定/条件的测试方法,同时进行了大量实验。认真研究明白了子数组最大和的求法。并且已经可以熟练进行代码测试,对测试的思想以及测试工具都有了更深一步的掌握。我会在日后学习中多使用这个方法,为以后做准备。