首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >是否有更快、更其他的使用if语句的方法?

是否有更快、更其他的使用if语句的方法?
EN

Stack Overflow用户
提问于 2022-01-31 15:25:22
回答 2查看 179关注 0票数 1

这是我的第一个迷你项目(我是中级c++程序员)

我想练习使用if语句,因为我想找到命令的范围,以及我可以使用它做什么。

然而,在我的整个程序中,我总是非常生气,因为我不得不编写所有这些代码来执行一个简单的任务。

代码的基础是用户输入他们的出生月份,程序输出他们与占星术相关的符号和意义。我的问题是,是否有办法,我可以执行相同的任务,但以较少的代码?有什么命令我可以用吗?

在我的cs1课程中,我们最近学习了开关案例。我在想,我可以用开关箱来解决我有过的一个问题,准确性。

提高用户b-天的准确性.与其使用大量的if语句,这些语句只能查找特定的月份(或者更多的if's月和日),我可以用一个例子来说明“1月1日至20日”,然而,现在我只想让更准确地描述一个月。*我是否可以使用更多的if语句,或者在这种情况下,如果用户说<20,那么它们就是水瓶座?

除了切换情况之外,还有什么不同的方法可以做这个程序吗?

代码语言:javascript
复制
    string user_month;
    cout << "This program currently accepts these months in this spelling\n";
    cout << "january, february, march\n\n";

    cout << "Whats the month of your birthday? (lowercase)\n";
    getline(cin, user_month);

    cout << endl;
    cout << user_name << " ... You are about to see your astrological sign and its qualities.\n";
    cout << "Know that they might not be truly accurate and this is just for fun.\n\n";

    if (user_month == "january")
    {
        ;
        cout << endl;
        cout << "You are a Capricorn.\n";
        cout << "Capricorns are usually hardworking, tenacious, diligent, and responsible\n";
        cout << "No matter what the job is, you'll get it done to the best of your ability.\n";
        cout << "Even if you don t have a natural aptitude for a skill, you won t stop working until you ve mastered "
                "it\n.";
    }

    if (user_month == "february")
    {

        cout << endl;
        cout << "You are a Aqaurius.\n";
        cout << "An Aquarius ascribes to a progressive ideology. \n";
        cout << "Because of this you are willing to let go of ";
        cout << "past traditions that no longer serve the people of the future.\n";
        cout << "You aren t content with the answer 'but that s the way it s always been done.' \n";
        cout << "You are willing to try new things, because you know that even if they fail, \n";
        cout << "you know that your getting closer to the right solution.\n";
    }

    if (user_month == "march")
    {

        cout << endl;
        cout << "You are an Aries.\n";
        cout << "At your core, you do what they want and do things your way.\n";
        cout << "You are unafraid of conflict, highly competitive, honest and direct.\n";
        cout << "An Aries is not weighed down by the freedom of choice, and is the sign that is least conflicted about "
                "what they want.\n";
        cout << "You might throw themselves at the world eagerly and without fear.\n";
        cout << "It is one of your most commendable qualities, but also what causes you a great deal of pain and "
                "grief.\n";
    }
    // yes I'm aware my code does not include all the months
    return 0;
}
EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2022-01-31 16:01:46

有时,当您必须以不同的方式处理n个不同的值时,您最终会得到一个开关或n个分支的if-级联。

但是通常,当您在所有分支中执行相同的操作(具有不同的数据)时,还有其他方法,例如查找表。

你想做什么?每个月,打印一篇课文。所以同样的动作,不同的数据。

在我们看更复杂的解决方案之前,让我们改进一下您已经学到的东西。

首先,您不需要每次重复cout,您可以链接流操作符<<

代码语言:javascript
复制
std::cout << "Hello\n" << "My name is Bob.\n" << "I like potatoes.\n";

更好的是,C++将合并“相邻”的字符串文本:

代码语言:javascript
复制
std::cout << "Hello\n" 
   "My name is Bob.\n"
   "I like potatoes.\n";

您还可以将这些大型文本块放入主变量之外的变量中,因此您看不到它们:

代码语言:javascript
复制
const char *capricorn = "You are a Capricorn.\n"
                        "Capricorns are hard...";

因此,您最终得到的代码如下:

代码语言:javascript
复制
string user_month;
getline(cin, user_month);
if (user_month == "january") {
    cout << capricorn;
} else if (user_month == "february") {
    cout << aquarius;
} else if (// etc...

读起来容易一点。现在我们看到我们节目的结构更清晰了。我们只想根据月份的情况进行cout

现在,有些事情你还没学到。例如,使用"map“(查找表):

代码语言:javascript
复制
#include <unordered_map>

// In your function
// Map of key-value pairs
std::unordered_map<std::string, std::string> um = 
{ {"january", "You are a Capricorn\n etc etc\n"} };

// Read month, then:
auto res = um.find(user_month);
if (res != um.end()) {
    // Found in map. res->first is key, res->second is value.
    std::cout << res->second;
} else {
    // Invalid month
    std::cout << "Error: invalid input";
}

另一种方法是将字符串存储在数组中,并将月份映射到数组索引(0-11)。但你也需要一个如果-级联,所以也许这违背了目的。

请注意,对于实际的黄道星座来说,任务会更困难一些,因为它们不是关于月份,而是日期范围(例如,3月21日)。-4月19日)。

票数 4
EN

Stack Overflow用户

发布于 2022-01-31 15:56:02

这是我怎么安排的。

我将使用std::map从月份名称映射到要与其关联的输出。

std::map::find将执行查找,并返回一个月的键值对和相关输出的迭代器,如果找不到,则返回一个结束迭代器。

std::optional是一种有值或无值的好方法,它比抛出异常要轻一些。

最后,充分利用函数,用可以理解的部分描述您的程序。

代码语言:javascript
复制
#include <optional>
#include <string>
#include <iostream>
#include <map>

std::map<std::string, std::string> signs = {
    { "january", "You are a capricorn..." },
    { "february", "You are an Aquarius..." },
    // ...
};

std::string getUserInput() {
    std::string input;
    getline(std::cin, input);
    return input;
}

std::optional<std::string> tryGetOutput(const std::string& month) {
    auto it = signs.find(month);
    if (it == signs.end()) return {};
    return it->second;
}

int main() {
    std::string input = getUserInput();
    std::optional<std::string> output = tryGetOutput(input);
    if (!output.has_value()) {
        std::cout << "unknown month" << std::endl;
        return -1;
    }
    std::cout << output.value() << std::endl;
}
票数 2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/70928438

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档