计数器控制的while循环(C++/python版)

常见的编程错误:

  • 浮点值是近似的,如果用浮点值变量控制计数器循环,那么会产生不精确的计数器值,并导致对终止条件的不准确测试

错误预防技巧:

  • 使用整数值控制计数器循环

良好的编程习惯:

  • 在每条控制语句的前后加入空行,可以使它在程序中突出显示
  • 过多层的嵌套会使程序难以理解,设法避免使用超过三层的嵌套
  • 在控制语句之上和下留有垂直的间距,以及控制语句的体缩进排列在其头部内,可以使程序呈现出一种二维的外观,非常有效地提高了程序的可读性

C++版本

// Counter-controlled repetition
#include <iostream>

using namespace std;

int main()
{
    int counter = 1; // declare and initialize control variable

    while(counter <=10)     // loop-continuation condition
    {
        cout << counter << " ";
        counter++;
    }   // end while

    cout << endl;   // output a newline
    return 0;   // successful termination
}   // end main

python版本

# -*- coding: utf-8 -*-
"""
Created on Sat Jun 07 21:13:07 2014

@author: Administrator
"""

# Counter-controlled repetition

counter = 1     # declare and initialize control variable

while(counter <=10):
    print counter,
    counter = counter + 1

print    # output a newline
原文地址:https://www.cnblogs.com/tmmuyb/p/3775368.html