快速上手C++系列:二、结构控制语句

发布时间:2015年08月11日 // 分类:代码 // 暂无评论

本教程示例程序基于Visual Studio 2013测试通过

二、C++的结构控制语句

while循环结构

基本结构:

while (条件) 循环体;

示例程序(计算1+2+3+4+5的结果):

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 1, s = 0;  // 声明变量并赋初始值
    while (i <= 5){
        s = s + i;
        ++i; // 前自增操作符,后面再说明。此处相当于 i=i+1
    }
    cout << s << endl;
    return 0;
}

程序执行结果:

15

for循环结构

基本结构:

for (初始化语句; 条件; 表达式) 循环体;

示例程序(计算1+2+3+4+5的结果):

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i = 1, s = 0;
    for (int i = 1; i <= 5; ++i){
        s = s + i;
    }
    cout << s << endl;
    return 0;
}

程序执行结果:

15

if条件语句

基本结构:

if (条件) {
    程序体
}
else if (条件) {
    程序体
}
else {
   程序体
}

示例程序(判断整数正负):

#include "stdafx.h"
#include "iostream"
using namespace std;

int _tmain(int argc, _TCHAR* argv[])
{
    int i;
    cin >> i;
    if (i > 0){
        cout << "+" << endl;
    }
    else if (i < 0){
        cout << "-" << endl;
    }
    else{
        cout << "0" << endl;
    }

    return 0;
}

程序执行结果1:

10                         // 此行为用户输入
+

程序执行结果2:

0                         // 此行为用户输入
0

程序执行结果3:

-5                         // 此行为用户输入
-

本文固定链接
https://www.ywlib.com/archives/23.html

标签
快速上手C++系列, c++, while, for, if, 结构控制语句

添加新评论 »