很多時候的重複執行,是我們知道需要執行多少次。比如那道高斯經典的從1加到100的題目,用代碼模拟高斯的同學的計算模型為如下
static void Main(string[] args)
{
int result = 0;
for (int i = 1; i <= 100; i++)
{
//1 + 2 + 3 + 4 + 5 + + 97 + 98 + 99 + 100
result += i;
}
System.Console.WriteLine(result);
}
for 語句重複執行括起來的語句,如下所述:
首先,計算變量 i 的初始值。
然後,隻要 i 的值小于或等于 100,條件計算結果就為 true。此時,将執行result += i; 語句并重新計算 i。
當 i 大于 100 時,條件變成 false 并且控制傳遞到循環外部。
是以用代碼模拟高斯這個天才的計算模型為如下
class Program
static void Main(string[] args)
int result = 0;
for (int i = 1; i <= 100; i++)
{
result += i;
}
System.Console.WriteLine("計算了100次,結果是:{0}", result);
result = 0;
for (int i = 1; i <= 50; i++)
result += i + (100 - i + 1);//1+100=101,2+99=101,3+98=101
System.Console.WriteLine("計算了50次,結果是:{0}", result);
初學者注意:
無論因為什麼原因,都不要試圖在for循環體内改變計數器的值。for的含義是重複的作一些事情,當你确定是需要重複的作的時候,才使用for循環語句。
本文轉自shyleoking 51CTO部落格,原文連結:http://blog.51cto.com/shyleoking/805196