計算與軟件工程作業三
要求:數組中最大子數組的和
用類/函數來實現
需求:希望返回 3 種信息
最大子數組的和
最大子數組開始的下標
最大子數組結束的下標
從文本文件中讀輸入的數據,熟悉文件操作, 文件有兩種數據
第一個數字:這次測試中有多少個數據, 數字后面是冒號。
后續數字: 每個數據的值,用逗號隔開
比如
文件內容:
17: -32, -10, 33, -23, 32, -12, 41, -12, 1, 3, 5, -98, 70, -21, 10, -9, 61
輸出
sum = 71
程序代碼
//FMax.cpp
#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 = 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;
}
運行截圖
單元測試代碼
//unittest1.cpp
#include "stdafx.h"
#include "CppUnitTest.h"
#include "Fmax.cpp"
using namespace Microsoft::VisualStudio::CppUnitTestFramework;
namespace UnitTest1
{
TEST_CLASS(UnitTest1)
{
public:
TEST_METHOD(TestMethod1)
{
int a[]={3,4,2};
Assert::AreEqual(9,getmax(a,3));
// TODO: 在此輸入測試代碼
}
};
}
測試截圖
小結
進行單元測試時,單元測試文件unittest1.cpp無法打開文件的問題,之后更改他的屬性VC++包含目錄解決。
目前對於軟件的認識尚淺,很多編程語言運用並不熟練,希望盡人事。相對來說,個人認為Java相對c語言簡單。希望在今后的學習中,能夠盡量補缺自己的短板。增加就業優勢。
碼雲鏈接:https://gitee.com/if_evening/fmax2