![](/img/trans.png)
[英]How can I avoid code duplication in C# while and do-while loops?
[英]Issues with looping code and do-while loops (c#)
static double calculateTotals(double a)
{
double transfee = a * .01;
double total = a + transfee;
return total;
}
static void Main(string[] args)
{
Console.WriteLine("How many dontations to process?");
int donations = Convert.ToInt16(Console.ReadLine());
int[] count = new int[] { donations + 1 };
int ct = 1;
int i = -1;
do
{
Console.WriteLine("Enter name: ");
string name = Console.ReadLine();
Console.WriteLine("Enter donation amount: ");
double amount = Convert.ToDouble(Console.ReadLine());
double transfee = amount * .01;
i++;
ct = count[i += 1];
Console.WriteLine(name + "\t" + amount + "\t" + transfee);
} while (i < donations);
Console.WriteLine("TOTALS:" + "\t" + calculateTotals(amount) + "\t" + transfee);
Console.ReadLine();
}
}
你好。 我是編碼的初學者,因此如果嘗試不當,我深表歉意。
我正在嘗試制作一個記錄個人捐贈金額,計算交易費用並輸出每個人結果的應用程序。 最后,我將創建最后一行輸出,其中將說明捐贈總額和交易費用總額。
我目前不確定如何在我的循環中正確實現數組,也不確定循環是否在總體上得到了優化。
同樣,我是初學者。 我為此類代碼表示歉意,但我希望對這些內容進行一些說明。
謝謝!
首先,您的數組聲明語法錯誤。 看到這個鏈接 。
因此應為int[] count = new int[donations+1];
其次,您需要在循環外聲明並實例化數量和流量變量。
double transfee = 0.0F;
double amount = 0.0F;
do
{
...
amount = Convert.ToDouble(Console.ReadLine());
transfee = amount * .01;
...
} while (i < donations);
這應該是足夠的信息,可以讓您再次嘗試。 既然您正在學習,我認為沒有人會真正為您提供答案,而您所做的工作正是您要設法解決的:)
您的代碼:
int i = -1;
do
{
...
i++;
ct = count[i += 1];
...
} while (i < donations);
您實際上將i增大了兩倍 ,然后從count [i]中獲取分配給ct變量的值
看到這個例子:
int[] count = new int[3];
count[0] = 0;
count[1] = 1;
count[2] = 2;
int i = -1;
do
{
i++;
int x = count[i += 1];
Console.WriteLine(x);
} while (i < 3);
它將導致IndexOutOfRangeException
說明:
第一循環:
i++; // i increased 1, so i = 0
int x = count[i += 1]; // i increased 1, so i = 1, then get count[1] assign to x, x is 1
第二循環:
i++; // i increased 1, so i = 2
int x = count[i += 1]; // i increased 1, so i = 3, then get count[3] assign to x
count [3]導致IndexOutOfRangeException
像count [i + = 1]之類的東西會使您的代碼更難以維護,我認為,如果可能的話,應避免使用它,並嘗試盡可能地將其寫得很明確。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.