我正在嘗試構建一個退休計算器,以此來提供一些有用的東西並更好地學習C#。目前,我正在嘗試使用動態數量的行/列構建DataTable。用C#編寫一個DataTable,每次只寫一列
對於上下文,我要求用戶提供一些關於工資,投資百分比和預期投資回報率的信息。我還有其他一些東西,但這不是我所遇到的問題的一部分。因爲我需要的數據表的列數是未知的,直到公式運行(+ for循環完成時),我在做DataColumns時遇到問題。希望下面的代碼將有所幫助。
我真的試圖一次構建表一列。我意識到我可以一次一次地將它建立起來,因爲退休前的年份(歲退休年齡)是已知的,但我不想和我想了解更多。對於縮進和評論感到抱歉。我試圖在那裏留下一些我評論的編碼嘗試。謝謝你的幫助。
public double calcROI()
{
double testROI = 0.00;
double tempRetireAmount = 0;
double adjustRetire = goalAmount * (1 + (Math.Pow(inflation,yearsRetire)));
// Loop through ROI values until the calculated retire amount with the test ROI
// is greater than the target amount adjusted for inflation
while (tempRetireAmount < adjustRetire)
{
//Increment ROI by 1% per while iteration
testROI += .01;
//Make a new Column to hold the values for ROI for this while iteration
//dtMain.Columns.Add(Convert.ToString(testROI));
//DataColumn tempdc = new DataColumn(Convert.ToString(testROI));
//Loop through the number of years entered by user and see the amount
//at Retirement with current ROI
for (int i = 0; i < yearsRetire; i++)
{
//Main formula to calculate amount after i years
tempRetireAmount = (tempRetireAmount + salary*savingsPct) * (1 + testROI);
// Add value for this year/ROI to table/column
//DataRow dr = .NewRow();
//dr tempRetireAmount;
//tempdc[i] = tempRetireAmount;
}
//Need to add column of data to my Main DataTable
//dtMain.Rows.Add(dr);
//dtMain.Columns.Add(tempdc);
}
return testROI;
}
更新:只是作爲一個說明,我絕對不是說這是最好的辦法,因爲我的出路我所知默認區。我通常只是建立一個最大大小的矩陣(數組[maxrows] [maxcols])並填充它。我試圖少思維C,並使用C#的一些功能。如果有更好的方法,我很樂意改變這項技術。謝謝。
因此,在這種情況下,我將建立雙打的動態數組?或者我會構建雙打的動態矩陣。這個最終目標將會進入GUI的DataGrid視圖。 – Awaken 2010-03-24 15:32:36