简体   繁体   English

有人可以在我的代码中找到与 C++ 中的 IF STATEMENT 相关的问题吗?

[英]Can someone find the problem in my code related to IF STATEMENT in C++?

#include <iostream>
using namespace std;
int max_of_four(int q, int w, int e, int r)
{
    int x;
    if( q > w &&  q > e &&  q > r)
        {int x = q;}
    else if( w > q &&  w > e && w > r)
        {int x = w;}
    else if( e > w &&  e > q &&  e > r)
        {int x = e;}
    else if( r > w &&  r > e &&  r > q)
        {int x = r;}
    else{x = 0;}   
    return x;
}
int main() {
    int a, b, c, d;
    cin >> a >> b >> c >> d;
    cout << max_of_four(a, b, c, d);
    return 0;
}

it always outputs 0, no matter what the input is.无论输入是什么,它总是输出 0。

I suppose the I am missing something in the if statement condition, someone please help!我想我在if statement条件中遗漏了一些东西,请有人帮忙!

In the if's int x = q;在 if 的int x = q; defines a new variable x and does not modify the x you return later.定义了一个新变量x并且修改您稍后返回的x

You probably just want x = q;你可能只想要x = q; to assign a new value to x .x分配一个新值。 This also applies to the other if's.这也适用于其他如果。

Or you could skip the assignment alltogether:或者您可以一起跳过作业:

int max_of_four(int q, int w, int e, int r)
{
    if( q > w &&  q > e &&  q > r)
        { return q; }
    else if( w > q &&  w > e && w > r)
        { return w; }
    else if( e > w &&  e > q &&  e > r)
        { return e; }
    else if( r > w &&  r > e &&  r > q)
        { return r; }

    return 0;
}

Actually, if you have C++11 or later, then std::max() can take an initializer list as its argument(s):实际上,如果您有C++11或更高版本,则std::max()可以将初始化列表作为其参数:

int max_of_four(int q, int w, int e, int r)
{
    return std::max({ q, w, e, r }); // Need to #include <algorithm> for std::max
}

Apart from redefinition of variable x, your test conditions, could be trimmed, are insufficient when values of q, w, e or r are same.除了重新定义变量 x 之外,当 q、w、e 或 r 的值相同时,您的测试条件可能会被修剪是不够的。 Also logically the return value should be either of the four variables but it should never return a zero.同样从逻辑上讲,返回值应该是四个变量中的任何一个,但它永远不应该返回零。

   int max_of_four(int q, int w, int e, int r)
   {
       int max = q;
       if (w > max ) max = w;
       if (e > max ) max = e;
       if (r > max ) max = r;
       return max;
   }

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

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