軟件工程第三次作業(yè)
題目選擇
題目(1):最大連續(xù)子數(shù)組和(最大子段和)
問(wèn)題: 給定n個(gè)整數(shù)(可能為負(fù)數(shù))組成的序列a[1],a[2],a[3],…,a[n],求該序列如a[i]+a[i+1]+…+a[j]的子段和的最大值。當(dāng)所給的整數(shù)均為負(fù)數(shù)時(shí)定義子段和為0,依此定義,所求的最優(yōu)值為: Max{0,a[i]+a[i+1]+…+a[j]},1<=i<=j<=n
例如,當(dāng)(a[1],a[2],a[3],a[4],a[5],a[6])=(-2,11,-4,13,-5,-2)時(shí),最大子段和為20。
樣例代碼:Coding.net
根據(jù)題目,代碼如下
package com.edu.sau;
/**
*
* @author HuangShuYe
* @version 1.0
*
*/
public class myArray {
public static void main(String[] args)
{
int result = maxSubSum(new int[] {1,2,3,4,5,6});
System.out.printf("%d",result);
}
/**
*
* @param list 數(shù)組
* @return 最大字段和
*/
public static int maxSubSum(int[] list)
{
int n = list.length;
int currSum = 0;
int maxSum = 0;
for (int i = 0; i < n; i++)
{
currSum+= list[i];
if (currSum > maxSum )
{
maxSum = currSum;
}
if (currSum < 0)
{
currSum = 0;
}
}
return maxSum;
}
}
選擇測(cè)試方法、設(shè)計(jì)測(cè)試用例
流程圖如下

本次使用選擇條件組合覆蓋的測(cè)試方法
有流程圖可知共有兩個(gè)判斷條件,所以有2^2=4種組合,舍棄不可能的情況共有三種:
?1.currSum>maxSum,currSum>=0
?2.currSum<=maxSum,currSum<0
?3.currSum<=maxSum,currSum>=0
因此設(shè)計(jì)測(cè)試用例如下:

利用自動(dòng)測(cè)試工具對(duì)程序進(jìn)行測(cè)試
測(cè)試代碼如下
package com.edu.test;
import static org.junit.Assert.*;
import org.junit.Before;
import org.junit.Test;
import com.edu.sau.myArray;
/**
*
* @author HuangShuYe
*
*/
public class myArrayTest {
@Test
public void testMaxSubSum()
{
assertEquals(10, myArray.maxSubSum(new int[] {1,2,3,4}));
}
@Test
public void testMaxSubSum1()
{
assertEquals(6, myArray.maxSubSum(new int[] {-11,1,2,3}));
}
@Test
public void testMaxSubSum2()
{
assertEquals(7, myArray.maxSubSum(new int[] {3,-1,2,3}));
}
}
測(cè)試運(yùn)行結(jié)果

如圖所示,按照上圖中的三個(gè)條件組合覆蓋測(cè)試用例依次測(cè)試,測(cè)試全部通過(guò)。
posted on 2018-04-01 19:10 SYBlog 閱讀(209) 評(píng)論(0) 收藏 舉報(bào)
浙公網(wǎng)安備 33010602011771號(hào)