以文本方式查看主题

-  W3CHINA.ORG讨论区 - 语义网·描述逻辑·本体·RDF·OWL  (http://bbs.xml.org.cn/index.asp)
--  『 编程心得 』   (http://bbs.xml.org.cn/list.asp?boardid=42)
----  不用if,用数组。  (http://bbs.xml.org.cn/dispbbs.asp?boardid=42&rootid=&id=87516)


--  作者:葛靖青001
--  发布时间:11/7/2010 11:09:00 AM

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


W 3 C h i n a ( since 2003 ) 旗 下 站 点
苏ICP备05006046号《全国人大常委会关于维护互联网安全的决定》《计算机信息网络国际联网安全保护管理办法》
31.250ms