You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++多条件if语句优化:如何用单个判断匹配多个整数值

当然有办法啦!不用写一堆重复的if语句,给你几个实用的解决方案,从简单直接到优雅高效都涵盖了:

方案1:使用逻辑或运算符(最直观的写法)

把多个判断条件用||(逻辑或)连接起来,一个if就能搞定所有匹配:

#include <iostream>
using namespace std;
int main() {
    int year;
    cin >> year;
    // 一次性判断所有鼠年年份
    if (year == 2008 || year == 1996 || year == 1984 || year == 1972 || year == 1960) {
        cout << "The year " << year << " is the year of the Rat";
    }
    return 0;
}

这个方法适合需要匹配的数值数量不多的场景,代码简洁易懂,维护起来也方便。

方案2:用集合容器存储目标值

如果需要匹配的数值特别多,把它们放进一个std::unordered_set(或者std::set)里,通过查找操作判断是否存在:

#include <iostream>
#include <unordered_set>
using namespace std;
int main() {
    int year;
    cin >> year;
    // 把所有鼠年年份存入集合
    unordered_set<int> rat_years = {2008, 1996, 1984, 1972, 1960, 1948, 1936};
    // 检查输入年份是否在集合中
    if (rat_years.find(year) != rat_years.end()) {
        cout << "The year " << year << " is the year of the Rat";
    }
    return 0;
}

这种方式的优势在于后续增删目标年份时,只需要修改集合的初始化代码,不用碰判断逻辑,扩展性很强。

方案3:利用生肖的循环规律(最优解)

生肖每12年循环一次,而鼠年的年份满足(year - 4) % 12 == 0(公元4年是鼠年,你可以验证下:2008-4=2004,2004除以12刚好整除)。用这个规律的话,不管哪一年都能直接判断,完全不用罗列所有年份:

#include <iostream>
using namespace std;
int main() {
    int year;
    cin >> year;
    // 利用12年循环的规律判断鼠年
    if ((year - 4) % 12 == 0) {
        cout << "The year " << year << " is the year of the Rat";
    }
    return 0;
}

这个方法既不用写一堆条件,也不需要额外的容器,计算量极小,绝对是处理生肖判断这类循环问题的最优选择。

内容的提问来源于stack exchange,提问作者Levi W.

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.25 08:30:58