巧用数组减少if语句

  假设我们要写一个判断用户输入整数奇偶性的程序,可以用以下代码实现:

 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
 * Author:            Antigloss at http://stdcpp.cn
 * 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;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值