1 / 18

第 2 章 程序的灵魂 ----- 算法

第 2 章 程序的灵魂 ----- 算法. (1) 对数据的描述 数据结构 ( 数据的类型和数据的组织形式 ) (2) 对操作的描述 算法 ( 解决一个问题的方法和步骤 ) 程序 = 算法 + 数据结构 + 程序设计方法 + 语言工具和环境 例 : 求和 1+2+3+…+100. 算法举例. 例 1 求 5 !( 1×2×3×4×5 ) s1 , 1→p s2 , 2 → I s3 , P × i → p s4 , I+1 → I s5 ,输出 p. 完整的算法.

erwin
Download Presentation

第 2 章 程序的灵魂 ----- 算法

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 第2章 程序的灵魂-----算法 (1) 对数据的描述 数据结构(数据的类型和数据的组织形式) (2) 对操作的描述 算法(解决一个问题的方法和步骤) 程序=算法+数据结构+程序设计方法+语言工具和环境 例:求和1+2+3+…+100

  2. 算法举例 例1 求5!(1×2×3×4×5) s1, 1→p s2, 2 → I s3, P × i → p s4, I+1 → I s5,输出p

  3. 完整的算法 s1,1→p s2,2 → Is3,当I<=5为真时到s4;为假时到s7s4,P × i → p s5,I+1 → Is6,转到s3s7, 输出p

  4. 开始 1→p 2 → I I<=5 f t 循环 输出p P × i → p 结束 I+1 → I N-S图表示 流程图表示

  5. 计算机语言表示 Main() { int p,I; p=1; I=2; while (I<=5) {p=p*I; I++;} printf(“%d”,p); }

  6. 例2 50个学生,打印成绩大于等于80的学生的学号和成绩。 s1,I=1 s2, I<=50为真时到s3;为假时到s6 s3, gi>=80为真时打印ni和gi;为假时空操作 s4, I=I+1 s5, 转到s2 s6, 结束

  7. 开始 1→i I<=50 f t Gi>=80 f t 打印ni和gi I+1 → I N-S图表示 结束 流程图表示

  8. 伪代码表示 BEGIN (算法开始) I=1; While I<=50 {input n1 and gi I=I+1; } I=1; while I<=50 {if gi>=80 print ni and gi I=I+1 } END(算法结束)

  9. 三种基本结构的n-s图表示 顺序结构 选择结构 当型循环结构 直到型循环构

  10. 例4 求1-1/2+1/3-1/4+…+1/99-1/00 算法可表示如下: S1, sign=1 S2, sum=1 S3, deno==2 S4, sign=(-1)*sign S5, term=sign*(1/deno) S6, sum=sum+term S7, deno=deno+1 S8, 若deno<=100返回s4,否则算法结束

  11. 开始 Sum=1 Deno=2 sign-=1 sign=(-1)*sign term=sign*(1/deno) sum=sum+term deno=deno+1 N-S图表示 流程图表示 N Deno>100 Y 结束

  12. 计算机语言表示 Main() { int sign=1; float deno=2.0;,sum=1.0, term; while (deno<=100) {sign=-sign; term=sign/deno; sum=sum+term; deno=deno+1;} Printf(“%f”,sum);} 习题:有一分数序列:2/1,3/2,5/3,8/5,13/8,21/13… 求出这个数列的前20项之和.

  13. 例5:对于一个大于或等于3的正整数,判断它是不是一个素数例5:对于一个大于或等于3的正整数,判断它是不是一个素数 S1: 输入n的值 s2: I=2(I作为除数) S3: N被I除,得余数r S4: 如果r=0,表示n能被I整除,则打印n”不是素数“,算法结束;否则转到s5 S5: I=I+1 S6: 如果I<=n-1,返回s3;否则打印n”是素数“,然后结束.

  14. N-S图表示

  15. 计算机语言表示 # include <math.h> Main() { int n,I,k; scanf(“%d”,&n); k=sqrt(n); for(I=2;I<=k;I++) if (n%I==0) break; if (I>k) printf(“%d is a prime number”,n); else printf(“%d is not a prime number”,n); }

  16. 结构化程序设计方法 例6:用筛法(埃拉托色尼筛法)求1-200之间的所有素数 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20………….200 A: B: C:

  17. B: A: B1 B2 B3 D C: 算法的进一步细化

  18. D: E: E F F: G: 算法的进一步细化

More Related