文档详情

C++语言程序设计(清华大学郑莉)_(2).ppt

发布:2019-04-05约1.47万字共89页下载文档
文本预览下载声明
* * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * * 4 * 5 * * * * * * * * * * * * * * * * * * * * * * * * * * * 对比下列程序: 程序1: #includeiostream using namespace std; int main() { int i,sum(0); cini; while(i=10) { sum+=i; i++; } coutsum=sum endl; } 算法的基本控制结构 程序2: #includeiostream using namespace std; int main() { int i, sum(0); cini; do{ sum+=i; i++; }while(i=10); coutsum=sum endl; } * * for 语句 语法形式 for (表达式1;表达式2;表达式3) 语句 循环前先求解 为true时执行循环体 每次执行完循环体后求解 算法的基本控制结构 * 例2-8 输入一个整数,求出它的所有因子。 算法的基本控制结构 #include iostream using namespace std; int main() { int n, k; cout Enter a positive integer: ; cin n; cout Number n Factors ; for (k=1; k = n; k++) if (n % k == 0) cout k ; cout endl; } * 运行结果1: Enter a positive integer: 36 Number 36 Factors 1 2 3 4 6 9 12 18 36 运行结果2: Enter a positive integer: 7 Number 7 Factors 1 7 * * 例2-9 编写程序输出以下图案 * *** ***** ******* ***** *** * 算法的基本控制结构 #includeiostream using namespace std; int main() { int i,j,n=4; for(i=1;i=n;i++) //输出前4行图案 { for(j=1;j=30;j++) cout ; //在图案左侧空30列 for(j=1; j=8-2*i ;j++) cout ; for(j=1; j=2*i-1 ;j++) cout*; coutendl; } * for(i=1;i=n-1;i++) //输出后3行图案 { for(j=1;j=30;j++) cout ; //在图案左侧空30列 for(j=1; j=7-2*i ;j++) cout*; coutendl; } } * * 循环结构与选择结构相互嵌套 #includeiostream using namespace std; int main() { int n; for(n=100; n=200; n++) { if (n%3!=0) coutn; } } 算法的基本控制结构 * 例2-10 读入一系列整数,统计出正整数个数i和负整数个数j,读入0则结束。 分析: 需要读入一系列整数,但是整数个数不定,要在每次读入之后进行判断,因此使用while循环最为合适。循环控制条件应该是n!=0。由于要判断数的正负并分别进行统计,所以需要在循环内部嵌入选择结构。 算法的基本控制结构 #includeiostream using namespace std; int main() { int i=0,j=0,n; cout请输入若干整数(输入0则结束)
显示全部
相似文档