1、请看下面两个计算空格和换行符数目的代码片段:
//Version 1
while (cin.get(ch))
{
if(ch == ' ')
spaces++;
if(ch == '\n')
newlines++;
}
//Version 2
while (cin.get(ch))
{
if(ch == ' ')
spaces++;
else if(ch == '\n')
newlines++;
}
第二种格式比第一种好在哪里呢?
答:这两个版本将给出相同的答案,但是ifelse效率更高。因为如果第一个判断成立的话。第二种格式不会执行第二个判断,而第一种格式会执行第二个判断。
2、在下图程序中,用ch+1替换++ch将发生什么情况呢?
//ifelse.cpp -- using the if else statement
#include <iostream>
int main()
{
char ch;
std::cout <<"Typt,and I shall repeat.\n";
std::cin.get(ch);
while(ch != '.')
{
if(ch == '\n')
std::cout << ch;
else
std::cout << ++ch;
std::cin.get(ch);
}
std::cout << "\nPlease excuse the slight confusion.\n";
return 0;
}
答:++ch 和ch+1得到的数值相同。但++ch的类型为char,将作为字符打印,而ch+1是int类型(因为char和1相加),将作为