if语句
#include <iostream>
int main()
{
using namespace std;
char ch;
int spaces = 0;
int total = 0;
cin.get(ch);
while ( ch != '.')
{
if (ch == ' ')
//if测试条件也将被强制转化成bool值,因此0被转换成false,非零被转化成true。
++spaces;
++total;
cin.get(ch);
}
cout << spaces << " spaces, " << total;
cout << " characters total in sentence\n";
return 0;
}
hello,world.
0 spaces, 11 characters total in sentence
hello hello//<enter>
hello,world.
1 spaces, 23 characters total in sentence//第一行有12个字符,包括中间的空格和末尾的换行符,第二行有11个(除了末尾的句点)
if - else语句
#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);
}
//try ch + 1 instead of ++ch for interesting effect
cout << "\nPlease excuse the slight confusion.\n";
cin.get();
cin.get();
return 0;
}
guo.
hvp
Please excuse the slight confusion.
格式化if else语句
if else 中的两种操作必须是一条语句,如果需要多条语句,需要用大括号将它们括起来,组成一个代码块。c++不会自动将if和else之间的所有代码视为一个代码块,因此必须用大括号将这些语句组成一个语句块。
由于c++是自由格式语言,因此只要使用大括号将语句括起来,对大括号的位置没有任何限制,上面的书写格式是一种流行格式,下面是另一种流行格式。
if (ch == 'z'){
zorro++;
cout << "Another Zorro candidate\n";
}
else {
dull++;
cout << "Not a Zorro candidate\n";
}
第一种格式强调的时语句的块结构,这种是将语句块和关键字if和else更紧密地结合在一起。
if-if else-else结构
#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 agein: ";
else
cout << Fave << " is right!\n";
} while ( n != Fave);
//这里有技巧就是把表达式variable == value反转过来写成value == valiable
//原因是可以用来捕获把相等运算符误写成赋值运算符的错误,因为value是一个定值,不能将另一个值赋给他
return 0;
}
Enter a number in the range 1-100 to find my favorite number: 80
Too high -- guess agein: 30
Too high -- guess agein: 27
27 is right!