您的位置:首页 > 编程语言 > C语言/C++

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

2016-12-23 11:03 274 查看
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;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  C++