《清华大学c++讲义郑莉第2章C++简单程序设计.pptVIP

  • 3
  • 0
  • 约2.05万字
  • 约 86页
  • 2016-12-30 发布于北京
  • 举报

《清华大学c++讲义郑莉第2章C++简单程序设计.ppt

2.4.3 循环结构 ——while语句 * 2.4 算法的基本控制结构 —— 2.4.3 循环结构 例2-5 求自然数1~10之和 分析:本题需要用累加算法,累加过程是一个循环过程,可以用while语句实现。 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. 例2-5(续) * 2.4 算法的基本控制结构 —— 2.4.3 循环结构 #include iostream using namespace std; int main() { int i = 1, sum = 0; while (i = 10) { sum += i; //相当于sum = sum + i; i++; } cout sum = sum endl; return 0; } 运行结果: sum = 55 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. while语句(续) * 2.4 算法的基本控制结构—— 2.4.3 循环结构 形式 while (表达式) 语句 可以是复合语句,其中必须含有改变条件表达式值的语句。 执行顺序 先判断表达式的值,若为 true 时,执行语句。 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. do-while 语句 * 2.4 算法的基本控制结构 —— 2.4.3 循环结构 #include iostream using namespace std; int main() { int n, right_digit, newnum = 0; cout Enter the number: ; cin n; cout The number in reverse order is ; do { right_digit = n % 10; cout right_digit; n /= 10; //相当于n=n/10 } while (n != 0); cout endl; return 0; } 例2-6:输入一个数,将各位数字翻转后输出 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. 例2-6(续) * 2.4 算法的基本控制结构 —— 2.4.3 循环结构 运行结果: Enter the number: 365 The number in reverse order is 563 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. do-while 语句(续) * 2.4 算法的基本控制结构 —— 2.4.3 循环结构 一般形式 do 语句 while (表达式) 可以是复合语句,其中必须含有改变条件表达式值的语句。 执行顺序 先执行循环体语句,后判断条件。 表达式为 true 时,继续执行循环体 与while语句的比较: while 语句执行顺序 先判断表达式的值,为true时,再执行语句 Evaluation only. Created with Aspose.Slides for .NET 3.5 Client Profile 5.2.0.0. Copyright 2004-2011 Aspose Pty Ltd. 例2-7用do-while语句编程,求自然数1~10之和 //2_7.cpp #include iostream using namespace std; int main() { int i = 1, sum = 0; do { sum += i; i++; } while (i = 10); cout sum = su

文档评论(0)

1亿VIP精品文档

相关文档