[英]How to generate and display a sequence (loan exercise)
我想創建一個序列,其中:
a0 = 1100000
a1 = 1100000 * 1.012 - 25000
a2 = (1100000 * 1.012 - 25000) * 1.012 - 25000
a3 = (1100000 * 1.012 - 25000) * 1.012 - 25000) * 1.012 - 25000
...
問題是,它只能計算/顯示a1
(1088200),一百次。 (我想將它們全部存儲在名為ms的數組中)
下面是我想出的代碼:
double interest = 1.012;
int[] ms = new int[100];
for (int i = 0; i < ms.Length; i++)
{
int a0 = 1100000;
ms[i] = Convert.ToInt32(a0 * interest - 25000);
a0 = ms[i];
Console.WriteLine(ms[i]);
}
Console.ReadLine();
您在循環的每次迭代中聲明一個新的a0
變量,並始終使用值1100000對其進行初始化。如果要在循環內使用上一次迭代中的值,則需要在循環外進行聲明:
int a0 = 1100000;
for (int i = 0; i < ms.Length; i++)
{
ms[i] = Convert.ToInt32(a0 * interest - 25000);
a0 = ms[i];
Console.WriteLine(ms[i]);
}
請注意,每次迭代都會失去精度-您最好將a0
保留為double
精度(或decimal
),並且僅在存儲時進行轉換:
decimal interest = 1.012m;
decimal current = 1100000;
for (int i = 0; i < ms.Length; i++)
{
current = current * interest - 25000;
ms[i] = (int) current;
Console.WriteLine(ms[i]);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.