- 注册时间
- 2011-3-6
- 最后登录
- 1970-1-1
该用户从未签到
|
假设我们要写一个判断用户输入整数奇偶性的程序,可以用以下代码实现: long num;
cin >> num;
if ( num % 2L ) {
cout << "Odd!\n";
} else {
cout << "Even!\n";
}
但是这个 if 判断是没必要的,我们可以利用数组来避免: const char *msg[] = { "Even", "Odd" };
long num;
cin >> num;
cout << msg[num & 1L] << '\n'; // can also be `num % 2'
这种方法不仅对这个程序有效,不少别的应用也可以使用这个方法来减少 if 语句。这个方法也可以用于 C 程序。以下是奇偶判断程序完整代码: /*
* FileName: odd_or_even.cpp
* LastModifiedDate: 2005-7-22 22:30
* Purpose: Tell if a given number is odd or even
*/
#include <cstdlib> // for EXIT_SUCCESS
#include <iostream>
#include <limits> // for numeric_limits
// flush the input buffer
inline void flush_stdin()
{
std::cin.clear(); // clear error state of the stream
// clear data left at the input buffer
std::cin.ignore( std::numeric_limits< std::streamsize >::max(), '\n' );
} // end of flush_stdin
int main()
{
long num;
const char *msg[] = { "Even", "Odd" };
for (;;) {
std::cout << "Please input an integer(q to end): ";
if ( std::cin >> num ) {
std::cout << msg[num & 1L] << '\n'; // we can also use `num % 2L'
} else {
std::cin.clear(); // clear error state before reading from the input stream
if ( std::cin.get() == 'q' ) {
flush_stdin();
break;
}
std::cerr << "You should input an INTEGER!\n";
}
flush_stdin();
}
std::cout << "Thanks for using our product!\nPress ENTER to quit...";
std::cin.get();
return EXIT_SUCCESS;
} |
|