每次我 运行 时,同一个程序都会给出不同的输出

same program gives different outputs everytime I run

我尝试编写一个程序来输出 "YES" 是否每个 x 值或 y 值都相同。否则它给出输出 "NO"。逻辑是,如果所有 x 值的最大值与所有 x 值的最小值相同,则该值从未改变,因此所有 x 值都相同。 y 值相同。

但是,输出有时会给出正确的结果,有时则不会(对于相同的输入)。此外,输出不规则。 (例如2对3错5对1错等)

这是我的代码:

#include <iostream>
#include <climits>
using namespace std;

int main(){
    int n;
    int minX,minY=INT_MAX;
    int maxX,maxY=INT_MIN;
    cin>>n;
    while(n--){    //for the next n line
        int x,y;
        cin>>x>>y;
        maxX=max(maxX,x);
        //cout<<maxX<<" ";    //comments I write to find out what the heck is happening

        minX=min(minX,x);    // This value changes irregularly, which I suspect is the problem.
        //cout<<minX<<" ";

        maxY=max(maxY,y);
        //cout<<maxY<<" ";

        minY=min(minY,y);
        //cout<<minY<<endl;

    }
    if(maxX==minX||maxY==minY){    //If the x values or the y values are all the same, true
        cout<<"YES";
    }
    else{
        cout<<"NO";
    }
    return 0;
}

输入:

5
0 1
0 2
0 3
0 4
0 5

工作时的输出(我评论的 couts):

0 0 1 1
0 0 2 1
0 0 3 1
0 0 4 1
0 0 5 1
YES

它不起作用时的输出之一(带有我评论的 couts)

0 -1319458864 1 1   // Not all the wrong outputs are the same, each wrong output is different than the other wrong output.
0 -1319458864 2 1
0 -1319458864 3 1
0 -1319458864 4 1
0 -1319458864 5 1
NO

在这些行中

int minX,minY=INT_MAX;
int maxX,maxY=INT_MIN;
       ^

minXmaxX 从未 初始化。这是标准定义的 UB。无论你读到什么都是不可预测的——它通常是另一个进程留在那个内存块上的东西。

请注意 = 的优先级高于逗号,因此表达式的计算结果为

int (minX),(minY=INT_MAX);

实际上逗号在C++的所有运算符中的优先级最低。将它们更改为这些应该修复

int minX=INT_MAX,minY=INT_MAX;
int maxX=INT_MIN,maxY=INT_MIN;
         ^~~~~~~