首页 > 解决方案 > c++ min max 与引用调用相关的问题

问题描述

例如)样本 1
输入:100 500,正确结果:200 250,

例如)样本 2
输入:355 321,正确结果:177 642

像这样,较小的输入必须是 *2,而较大的输入必须是 /2。

并且必须按输入顺序打印(我称之为't','t2')

它看起来很简单,但我必须打印出来才能通过。ex) 355 首先通过,保存在 't' 中并修改,然后先打印。

首先,我尝试了 a'<'b? a:b 或 max() 但在 355 321 个案例中遇到了问题,所以我一直在简化函数

我的最终代码是这个(忽略非有效负载):

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void sout(int& , int&,int &max, int& min);

int main()
{

    int ma, mn;
    int t;
    cin >> t;
    int t2;
    cin >> t2;
    sout(t,t2,ma,mn) ;
    cout << t << ' ' << t2;
}
void sout(int& t, int& t2 ,int &ma, int& mn)
{
    if (t > t2) {
        t /= 2;
        t2 *= 2;
    }

    if (t < t2) {
        t2 /= 2;
        t *= 2;
    }
}

但是我在测试用例 355、321 中失败了。我的代码打印出 354、321。我的意思是 xxxx 人为什么 355 减少了 1 和 idk 发生了什么,我为什么通过其他测试用例?它只是相同的数字!

所以我尝试使用地址进行比较(因为我必须使用函数并使用引用调用)所以这部分是固定的:

   if (&t > &t2) {
                t /= 2;
                t2 *= 2;
            }

    if (&t < &t2) {
                t2 /= 2;
                t *= 2;
            }

然后它起作用了。但在其他情况下失败,例如 35, 3 -> 70, 1

谁能给我解释一下?我希望结构相同,因为我希望将好奇心的焦点固定在这里;

欢呼伙计们!

标签: c++algorithm

解决方案


由于您同时使用if这两个条件,因此在某些情况下,两者都将被执行。

// t = 355, t2 = 321
if (t > t2) {
    t /= 2;
    t2 *= 2;
    // t = 177, t2 = 642
}
// t = 177, t2 = 642
if (t < t2) {
    t2 /= 2;
    t *= 2;
    // t = 354 , t2 = 321
}
// return t = 354 , t2 = 321

用于else第二个条件。

#include <iostream>
#include <string>
#include <algorithm>
using namespace std;

void sout(int& , int&,int &max, int& min);

int main()
{

    int ma, mn;
    int t;
    cin >> t;
    int t2;
    cin >> t2;
    sout(t,t2,ma,mn) ;
    cout << t << ' ' << t2;
}
void sout(int& t, int& t2 ,int &ma, int& mn)
{
    if (t > t2) {
        t /= 2;
        t2 *= 2;
    }
    else {
        t2 /= 2;
        t *= 2;
    }
}

使用三元运算符:

void sout(int& t, int& t2 ,int &ma, int& mn)
{   
    (t < t2) ? (t*=2, t2/=2) : (t/=2, t2*=2);
}

推荐阅读