【C++】学习笔记二十一——if语句

本文通过三个程序示例介绍了C++中if语句、if-else语句及if-elseif-else结构的使用方法。第一个程序统计句子中的空格数;第二个程序演示了字符的输入与有条件地输出;第三个程序实现了一个简单的猜数字游戏。
if (test-condition)
    statement

程序6.1

#include<iostream>
int main()
{
    using namespace std;
    char ch;
    int spaces = 0;
    int total = 0;
    cin.get(ch);
    while (ch != '.')
    {
        if (ch == ' ')
            ++spaces;
        ++total;
        cin.get(ch);
    }
    cout << spaces << " spaces, " << total;
    cout << " characters total in sentence\n";
    system("pause");
    return 0;
}

这里写图片描述

1. if else语句

if (test-condition)         //如果测试条件为true或非0,将执行statement1,跳过statement2
    statement1
else                        //如果测试条件为false或0,将执行statement2
    statement2

程序6.2

#include<iostream>
int main()
{
    using namespace std;
    char ch;
    cout << "Type, and I shall repeat.\n";
    cin.get(ch);
    while (ch!='.')
    {
        if (ch == '\n')
            cout << ch;
        else
            cout << ++ch;
        cin.get(ch);
    }

    cout << "\nPlease excuse the slight confusion.\n";
    system("pause");
    return 0;
}

这里写图片描述

if else中的两种操作都必须是一条语句,如果需要多条语句,需要用大括号将它们括起来,组成一个块语句。

2. if else if else结构

程序6.3

#include<iostream>
const int Fave = 27;
int main()
{
    using namespace std;
    int n;

    cout << "Enter a number in the range 1-100 to find ";
    cout << "my favorite number: ";
    do
    {
        cin >> n;
        if (n < Fave)
            cout << "Too low - - guess again: ";
        else if (n > Fave)
            cout << "Too high - - guess again: ";
        else
            cout << Fave << " is right!\n";
    } while (n != Fave);
    system("pause");
    return 0;
}
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值