【问题标题】:same program gives different outputs everytime I run [closed]每次我运行时,同一个程序都会给出不同的输出[关闭]
【发布时间】:2017-08-06 13:34:05
【问题描述】:

我尝试编写一个输出“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

【问题讨论】:

  • 你为什么使用这么多你不使用的包含?
  • 你永远不会初始化minXmaxX
  • ^ 这意味着阅读它们会使您的程序具有未定义的行为。

标签: c++ input output max min


【解决方案1】:

在这些行中

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;
         ^~~~~~~

【讨论】:

  • 每行放置一个变量(带初始化)也可以解决问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-12-06
  • 1970-01-01
  • 2021-10-17
  • 1970-01-01
  • 2020-12-17
  • 1970-01-01
相关资源
最近更新 更多