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;
}