這個作業要求在哪里 | 第三次作業 |
---|---|
我在這個課程的目標是 | 成功求數組中最大子數組的和 |
此作業在哪個具體方面幫我實現目標 | 運行了單元測試 |
其他參考文獻 | https://www.cnblogs.com/xinz/archive/2011/11/20/2255830.html |
gitee鏈接 | 代碼 |
單元測試要求#
- 開始:所有單元測試都失敗
- 改進程序,加入正確的邏輯,看到有單元測試通過,並且看到代碼覆蓋率的增加
- 重復, 直到所有單元測試都通過,代碼覆蓋率達到滿意的結果。
代碼#
#include<iostream>
#include<cstdlib>
using namespace std;
int getmax(int array[],int length)
{
int sum = 0;
int max = 0;
int startIndex = 0;
int endIndex = 0;
int newStartIndex = 0;
for (int i = 0; i < length; i++)
{
if (max < 0)
{
max = array[i];
newStartIndex = i;
}
else
{
max += array[i];
}
if (sum < max)
{
sum = max;
startIndex = newStartIndex;
endIndex = i;
}
}
return max;
}
int getstartIndex(int array[],int length)
{
int sum = 0;
int max = 0;
int startIndex = 0;
int endIndex = 0;
int newStartIndex = 0;
for (int i = 0; i < length; i++)
{
if (max < 0)
{
max = array[i];
newStartIndex = i;
}
else
{
max += array[i];
}
if (sum < max)
{
sum = max;
startIndex = newStartIndex;
endIndex = i;
}
}
return startIndex;
}
int getendIndex(int array[],int length)
{
int sum = 0;
int max = 0;
int startIndex = 0;
int endIndex = 0;
int newStartIndex = 0;
for (int i = 0; i < length; i++)
{
if (max < 0) //如果max < 0;
{
max = array[i];
newStartIndex = i;
}
else
{
max += array[i];
}
if (sum < max)
{
sum = max;
startIndex = newStartIndex;
endIndex = i;
}
}
return endIndex;
}
int main()
{
int length,i=0;
cout<<"請輸入個數:";
cin>>length;
cout<<"請輸入數組:";
int array[1000]={0};
for(i=0;i<length;i++)
{
cin>>array[i];
}
cout<<"最大子數組的和為:"<<getmax(array,length)<<endl;
cout<<"最大子數組起始下標:"<<getstartIndex(array,length)<<endl;
cout<<"最大子數組結束下標:"<<getendIndex(array,length)<<endl;
system("pause");
return 0;
}
單元測試#
#include "pch.h"
#include "CppUnitTest.h"
#include"max.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(getmax_Test)
{
//TODO: 在此輸入測試代碼
int data[] = { -32, -10, 33, -23, 32, -12, 41, -12, 1, 3, 5, -98, 70, -21, 10, -9, 61 };
Assert::AreEqual(111, getmax(a, 17));
}
};
}
博客作業#
總結##
在信息與計算科學專業前兩年的學習經歷中,學習了如c++,c語言,Java,matlab等項目技能,但是這些技能我都還處於入門階段,還需要在接下來一年多的學習中,增加自己的個人能力,多學多做才能有所進步。