简体   繁体   English

C ++中的if语句

[英]if statements in c++

So I have been writing in c++ for a few weeks now and can't help but feel that I am using too many if statements in my code. 所以我已经用C ++编写了几周了,不禁感到我在代码中使用了太多if语句。 I am aware of while, do while, and for loops but when given the scenario I always use if statements. 我知道while,do和for循环,但是在给定方案的情况下,我总是使用if语句。 I guess I am not exactly aware of how I could use a different method. 我想我不太清楚如何使用其他方法。 I just finished a project and there are if statements everywhere. 我刚刚完成一个项目,到处都有if语句。 Could one of you guys please explain to me how I can change some of these if statements into something different but still functional? 能否请你们向我解释一下如何将其中一些if语句更改为其他但仍可以起作用的内容? I am really just looking for guidance in the right direction. 我真的只是在寻找正确方向的指导。 Any help will be appreciated. 任何帮助将不胜感激。 Thank you guys! 感谢大伙们!

If statement #1 that bugs me: 如果语句1使我感到烦恼:

    if (x >= 1)
    {
        setx_Position(3);
        sety_Position(500);
        cout << "Soldier moves: " <<getx_Position()<<", "<<gety_Position()<< "   ";
        cout << endl;
    }
    else
    {
        cout << "Soldier moves: " <<getx_Position()<<", "<<gety_Position()<< "   ";
        cout << endl;
    }
    return 0;

Second if statement bugging me is : 第二个让我烦恼的语句是:

    a--;
    if (a >= 0)
    {
        cout << "Soldier fires weapon : Pistol " << "(" << a << " bullets left)" << endl;
    }
    else if (x <= 0)
    {
        cout << "Soldier fires weapon : NO WEAPON FIRED! (DEAD)" << endl;
    }
    return 0;

Both of these just feel lengthy and unnecessary to me. 这两个对我来说都是漫长而不必要的。 How could I get the same results with a much cleaner look? 如何获得更干净的外观相同的结果? Or is this the best way to do it? 还是这是最好的方法?

There's nothing wrong with having to use if statements, they're often a must when you need to perform an action conditionally. 不必使用if语句并没有错,当您需要有条件地执行操作时,它们通常是必须的。 As for improving your snippets, an obvious thing to do in the first one is to move the common sections of code outside the if-else block. 至于改进您的代码片段,在第一个步骤中显而易见的事情是将通用代码段移至if-else块之外。

if (x >= 1)
{
    setx_Position(3);
    sety_Position(500);
}
cout << "Soldier moves: " << getx_Position() << ", " << gety_Position() << "   ";
cout << endl;

The second one looks pretty good as is. 第二个看起来不错。 The only thing I see that could (arguably) be an improvement is to remove a--; 我唯一可以看到的(可能是)改进是删除a--; and change the if condition to if(--a >= 0) 并将if条件更改为if(--a >= 0)

好吧,图灵会为忠于原始图灵机的行为而感到自豪,但是在现代C ++中,您的武器库中还有其他武器,我建议您读一本有关模式的书,也许本书中没有“优化”或从片段中提出一些建议,这是没有意义的,因为如果不能真正影响您的生产技能,那么您就需要有关高级C ++技术的基础。

well an if statement is a very common thing to use in code, especially in logic heavy sections, such as game code. 在代码中,尤其是在逻辑繁重的部分(例如游戏代码)中使用if语句是很常见的事情。

in c++ one way to avoid lots of if blocks for different things is to use Polymorphism, or function pointers. 在c ++中,避免对不同事物使用大量if块的一种方法是使用多态性或函数指针。

switch statements can also be good. switch语句也可以。

I can't really see any better way of doing your two examples, except for the optimization of example one mentioned by Praetorian 除了优化Praetorian提到的第一个示例外,我真的看不到任何更好的方法来完成两个示例

A great deal depends upon what sort of logic you're willing to use to avoid an if statement. 很大程度上取决于您愿意使用哪种逻辑来避免使用if语句。

For example, let's consider your second example. 例如,让我们考虑第二个示例。 You really have pretty much the same actions in both legs of the if statement -- you mostly just supply different data to write to the output. 实际上,在if语句的两条腿上都具有几乎相同的动作-您大多只是提供不同的数据以写入输出。 If you don't mind some minor changes in wording, it's pretty easy to eliminate the if statement entirely: 如果您不介意措词上的一些细微变化,则完全消除if语句很容易:

static char const *prefixes[] = {
    "Soldier tries to fire (but has ",
    "Soldier fires Weapon: Pistol ("
};

std::cout << prefixes[--a >= 0] << a << " bullets left)\n";

It's a little hard to say whether I'd recommend this or not. 很难说我是否推荐这个。 At first glance, the code is obviously a lot simpler and cleaner -- no conditions or if statements to deal with at all. 乍一看,该代码显然更加简单和整洁-完全没有条件或if语句要处理。 At the same time, for somebody who's unaccustomed to this style, it would undoubtedly lead to some serious head-scratching. 同时,对于那些不习惯这种风格的人来说,无疑会导致严重的头疼。

please explain to me how I can change some of these if statements into something different but still functional? 请向我解释如何将其中一些if语句更改为其他但仍可以起作用的内容?

If you need to make decisions, you need if statements. 如果需要做出决定,则需要if语句。 Thing is, if you have many many of them littering the code I agree with you that you would want to think long and hard about how to make the code more readable by performing the logic in other ways. 问题是,如果您有很多人在乱扔代码,我同意您的观点,那么您将想一想,就如何通过以其他方式执行逻辑使代码更具可读性进行认真思考。 (Remember, (paraphrasing) code is mainly for reading; and only occasionally for the computer to execute). (请记住,(措辞)代码主要用于阅读;仅偶尔用于计算机执行)。 You probably don't want code that is too 'procedural', ie one long stream of C-like code. 您可能不希望代码过于“过程化”,即一长串类似C的代码。 Create classes/objects that react to your simulation, thus encapsulating much of the logic. 创建对您的模拟有反应的类/对象,从而封装许多逻辑。 And please, don't have massively nested if/else spaghetti. 而且,请不要大量嵌套意大利式面条。

Another reason to reduce the number of if's is that if blocks are the most likely parts of your code to contain bugs, and are the hardest to test. 减少if数量的另一个原因是,if块是代码中最有可能包含错误且最难测试的部分。 (You are writing tests, right?) (您正在编写测试,对吧?)

But as others have said, there's not enough context. 但是正如其他人所说,没有足够的背景信息。 Oh, and name your variables like "NumBulletsRemaining" instead of x or whatever :) 哦,将变量命名为“ NumBulletsRemaining”,而不是x或其他:)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM