[接招看題032] 用while語句求1~100的累計和。
/程序功能:求1~100的累計和/
幫你節約時間的源代碼:
main()
{ int i=1,sum=0; /*初始化循環控制變量i和累計器sum*/
while( i<=100 )
{ sum += i; /*實現累加*/
i++; /*循環控制變量i增1*/
}
printf("sum=%d\n",sum);/*while語句的下一條*/
}
內功心法,祝你超神!
(1)一般格式
while(循環繼續條件)
{ 循環體語句組;}
(2)執行過程
執行過程:
1)求解"循環繼續條件"表達式。如果其值爲非0,轉2);否則轉3)。
2)執行循環體語句組,然後轉1)。
3)執行while語句的下一條。即上述源代碼的printf語句。
顯然,while循環是for循環的一種簡化形式(缺省"變量賦初值"和"循環變量增值"表達式)。