2017-08-06 140 views
-4

我試着編寫一個程序,輸出「是」,每個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 
+4

爲什麼你使用soooooo許多包括你不使用? – Rakete1111

+5

你永遠不會初始化'minX'和'maxX'。 – Cornstalks

+0

^這意味着閱讀他們會留下未定義行爲的程序。 – StoryTeller

回答

0

在這些線路

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

每行放置一個變量(使用初始化)也將解決此問題。 –

相關問題