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

same program gives different outputs everytime I run

本文关键字:输出 程序 运行时      更新时间:2023-10-16

我尝试编写一个程序,无论每个x值或y值都相同,它都会输出"YES"。否则,它会给出输出"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;
^~~~~~~