【问题标题】:What is the difference between these two snippets of c++ code这两个c ++代码片段有什么区别
【发布时间】:2021-12-17 09:19:36
【问题描述】:

这些是我对 codeforces 问题的答案,我不知道为什么第一个 sn-p 给出了错误的答案。

第二个被接受了。

我想知道判断测试用例是否有问题,因为它们似乎给出了相同的输出。

问题说明如下:

给定 2 个区间的边界。打印它们的交点边界。

注意:边界是指区间的两端,即开始数和结束数。

输入: 只有一行包含两个区间 [l1,r1], [l2,r2] 其中 (1≤l1,l2,r1,r2≤109), (l1≤r1,l2≤r2)。

保证l1≤r1,l2≤r2。

输出: 如果这两个区间有交集,则打印其边界,否则打印-1。

片段 1

#include <bits/stdc++.h>

using namespace std;

int main()
{
    int a, b, c, d;
    int z;
    cin >> a >> b >> c >> d;
    if(a > b)
    {
        z = a;
        a = b;
        b = z;
    }
    if(c > d)
    {
        z = c;
        c = d;
        d = z;
    }
    if(c > b)
    {
        cout << -1;
    }
    else
    {
        cout << max(a, c) << " " << min(b, d);
    }
    return 0
}

片段 2

#include <bits/stdc++.h>
using namespace std;

int main()
{
    int l1 , r1 , l2 , r2;
    cin >> l1 >> r1 >> l2 >> r2;
    int _begin = max(l1,l2);
    int _end = min(r1,r2);
    if (_begin > _end)
        cout << -1;
    else
        cout << begin << " " << end;
    return 0;
}

【问题讨论】:

  • 查看你的变量并比较第二个 sn-p 如何使用它的变量。那里有一个非常明显的区别
  • 片段 1 的前两个 ifs 永远不会是真的。声明输入保证l1 &lt;= r1l2 &lt;= r2。这十二行实际上并没有做任何事情。
  • 不要成为“那个人”。给你的变量起有意义的名字。它使代码更易于阅读,并且使编译器更容易捕获琐碎的拼写错误。很难在代码中发现 bd 的转置。
  • #include &lt;bits/stdc++.h&gt; -- 不要这样做。包括正确的标题,在本例中为 #include &lt;iostream&gt;#include &lt;algorithm&gt;

标签: c++ if-statement max min intersection


【解决方案1】:

在第一个程序中,您只检查一个条件

if(c > b)
{
    cout << -1;
}

但您还需要检查以下条件

if ( d < a )
{
    cout << -1;
}

例如

if(c > b || d < a )
{
    cout << -1;
}
else
{
    //...
}

【讨论】:

    猜你喜欢
    • 2021-01-06
    • 1970-01-01
    • 2013-03-29
    • 1970-01-01
    • 1970-01-01
    • 2012-01-30
    • 2011-04-30
    • 1970-01-01
    相关资源
    最近更新 更多