用户可以使用 if 语句选择两个不同的数学公式

发布于 2025-01-19 22:31:13 字数 555 浏览 2 评论 0原文

#include <iostream>
using namespace std;

void funcOne()
{
    cout << "one";
}

void funcTwo()
{
    cout << "two";
}

int main()
{
    int vienadojums;

    cout << "Type [K] or [L]: ";
    cin >> output;
    
    if (output == 'K' || 'k')
    {
        funcOne();
    }
    else if (output == 'L' || 'l')
    {
         funcTwo();
    };

    


    return 0;
}

我输入的输入都没关系,它将始终输出funcone()。使用此代码,我想制作,因此用户可以通过输入[k]或[l]选择2个不同的数学问题公式。但是由于某种原因,无论您输入什么,它都会显示funcone()

#include <iostream>
using namespace std;

void funcOne()
{
    cout << "one";
}

void funcTwo()
{
    cout << "two";
}

int main()
{
    int vienadojums;

    cout << "Type [K] or [L]: ";
    cin >> output;
    
    if (output == 'K' || 'k')
    {
        funcOne();
    }
    else if (output == 'L' || 'l')
    {
         funcTwo();
    };

    


    return 0;
}

It doesn't matter what input I enter, it will always output funcOne(). With this code, I want to make, so user can choose 2 different math problem formulas by inputting [K] or [L]. But for some reason no matter what you enter it will show funcOne()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

温馨耳语 2025-01-26 22:31:13
if (output == 'K' || 'k')

如果:

  • 输出等于'k'

  • 'k'(不是零),

第二个条件始终评估为true。

您的想要是:

if ( ( output == 'K' ) || ( output == 'k' ) )

第二种条件相同。


我在这里假设一个编辑工件:

int vienadojums;

cout << "Type [K] or [L]: ";
cin >> output;

您从未定义输出,并且您从未使用过vienadojums。如果将这些内容是相同的变量,则您会期望从输入中获得int,而不是char(如稍后在代码中所假设的那样)。您的第一个条件始终评估到true不管用户输入什么,但您也必须修复此错误。

(Sidenote,当您读取int从用户输入中,请检查cin.fail(),以防用户使用 输入数字。


em > 围绕子表达,并在最严格的层面上启用编译器警告;只有通过告诉编译器明确您想要什么,您就会给编译器告诉您您可能在哪里犯了错误。编译器可以并且应该警告您以上所有内容。

if (output == 'K' || 'k')

This is true if:

  • output equals 'K'

or

  • 'k' (is not equal zero)

The second condition always evaluates to true.

What you want is:

if ( ( output == 'K' ) || ( output == 'k' ) )

Same for the second condition.


I assume an edit artifact here:

int vienadojums;

cout << "Type [K] or [L]: ";
cin >> output;

You never defined output, and you never used vienadojums. If those were meant to be the same variable, you would be expecting an int from input, not a char (as you assume later on in your code). This error is covered up by your first condition always evaluating to true regardless of what the user enters, but you will have to fix this as well.

(Sidenote, when you are reading int from user input, check cin.fail() in case the user did not enter digits. Same for C and scanf(), check that return value.)


The meta to take away here: Always put paranthesis around subexpressions, and enable compiler warnings at the strictest level possible; only by telling the compiler explicitly what you want do you give the compiler the opportunity to tell you where you might have erred. The compiler could, and should, have warned you of all of the above.

仅冇旳回忆 2025-01-26 22:31:13

在C ++中,字符文字(例如,'k')将在上下文中转换为布尔表达式,其中true是任何非零值(即值不是null code ' \ 0'†),false是空值。这在任何情况下都会发生在编译器中预期的布尔表达式中,例如,自然而然的是if-statement的条款。

因此,当您编写if(output =='k'||'k')时,右边的字符是上下文转换为布尔值的,并且该表达式在逻辑上等同于> if(output =='k'|| true),它将始终评估为true

编写本文的正确方法是if(output =='k'|| output =='k')

†这是null字符,'\ 0',而不是字符文字'0'0'

In C++, a character literal (for example, 'k') will contextually convert to a boolean expression, where true is any non-null value (i.e. the value is not the null character '\0'†), and false is the null value. This happens in any context where a boolean expression is expected by the compiler like, naturally, the clause of an if-statement.

So when you write if (output == 'K' || 'k'), the character literal on the right is contextually converted to a boolean value, and this expression is logically equivalent to if (output == 'K' || true), which will always evaluate to true.

The correct way to write this is if (output == 'K' || output == 'k').

† This is the null character, '\0', and NOT the character literal '0'

掩于岁月 2025-01-26 22:31:13

在您的if语句中,条件始终是正确的,因为:

[x]或true =&gt; true

[x] =&gt; (输出=='k')

'k'是一个真实的值

,无论output =='k'的结果如何

In your if statement the condition is always true because:

[x] or true => true

[x] => (output == 'K')

'k' is a truthy value

no matter the result of output == 'K'

孤独岁月 2025-01-26 22:31:13

声明变量vienadojums为具有类型char

char vienadojums;

并使用它而不是变量output,因为在if语句中,您将其与字符进行比较。

或者,而不是声明变量vienadojums

char vienadojums;

decalre

char output;

,然后更改IF语句中的条件,例如

if (output == 'K' || output == 'k')
{
    funcOne();
}
else if (output == 'L' || output == 'l')
{
     funcTwo();
};

,例如,例如此if语句

 if (output == 'K' || 'k')

始终评估到true true true true独立于存储在变量code> output 因为字符文字'k'不等于0

这是上述语句等同于

if ( ( output == 'K' ) || ( 'k' != 0 ) )

通常要注意的语句等同于当您具有许多功能时,您需要从中选择一个函数来调用该方法以使用语句不灵活。

相反,您可以将功能的所有功能和相应的标识符存储在容器中,例如在数组中。然后根据用户输入从容器中选择所需的功能。

例如,

#include <iostream>
#include <utility>
#include <iterator>
#include <algorithm>
#include <cctype>

void funcOne()
{
    std::cout << "one\n";
}

void funcTwo()
{
    std::cout << "two\n";
}

int main()
{
    std::pair<char, void( * )( void )> expressions[] =
    {
        { 'l', funcOne }, { 'k', funcTwo }
    };

    std::cout << "Type any of ";

    bool following = false;

    for (auto &[selection, func] : expressions)
    {
        if (following)
        {
            std::cout << ", ";
        }

        std::cout << '\'' << selection << '\'';
        following = true;
    }
    std::cout << " : ";

    char selection = '\0';

    std::cin >> selection;

    auto it = std::find_if( std::begin( expressions ), std::end( expressions ),
        [&]( const auto &item ) 
        { 
            return item.first == ::tolower( ( unsigned char )selection ); 
        } );

    if (it != std::end( expressions ))
    {
        it->second();
    }
    else
    {
        std::cout << "Invalid input.\n";
    }
}

程序输出可能看起来像

Type any of 'l', 'k' : L
one

Declare the variable vienadojums as having the type char

char vienadojums;

and use it instead of the variable output because in the if statement you are comparing it with characters.

Or instead of the declaration of the variable vienadojums

char vienadojums;

decalre

char output;

And change the conditions in the if statements like

if (output == 'K' || output == 'k')
{
    funcOne();
}
else if (output == 'L' || output == 'l')
{
     funcTwo();
};

Otherwise for example this if statement

 if (output == 'K' || 'k')

always evaluates to true independent on the value stored in the variable output because the character literal 'k' is not equal to 0.

That is the above if statement is equivalent to

if ( ( output == 'K' ) || ( 'k' != 0 ) )

Pay attention to that in general when you have many functions from which you need to select one function to call the approach with if statements is not flexible.

Instead you could store all functions and corresponding identifiers of the functions in a container for example in an array. And then select a required function from the container according to the user input.

For example

#include <iostream>
#include <utility>
#include <iterator>
#include <algorithm>
#include <cctype>

void funcOne()
{
    std::cout << "one\n";
}

void funcTwo()
{
    std::cout << "two\n";
}

int main()
{
    std::pair<char, void( * )( void )> expressions[] =
    {
        { 'l', funcOne }, { 'k', funcTwo }
    };

    std::cout << "Type any of ";

    bool following = false;

    for (auto &[selection, func] : expressions)
    {
        if (following)
        {
            std::cout << ", ";
        }

        std::cout << '\'' << selection << '\'';
        following = true;
    }
    std::cout << " : ";

    char selection = '\0';

    std::cin >> selection;

    auto it = std::find_if( std::begin( expressions ), std::end( expressions ),
        [&]( const auto &item ) 
        { 
            return item.first == ::tolower( ( unsigned char )selection ); 
        } );

    if (it != std::end( expressions ))
    {
        it->second();
    }
    else
    {
        std::cout << "Invalid input.\n";
    }
}

The program output might look like for example

Type any of 'l', 'k' : L
one
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文