gpt4 book ai didi

c++在添加两个绝对(正)值时得到负值

转载 作者:行者123 更新时间:2023-11-30 03:25:48 28 4
gpt4 key购买 nike

<分区>

我遇到了一个奇怪的问题。添加两个绝对(正)值时,我得到负值。我正在尝试通过编码游戏解决此练习(链接:https://www.codingame.com/ide/puzzle/network-cabling)。

我试过调试,我得到了这个:

X[i]: 19715507  X[j]: 938059973   // This one is good
temp: 918344466

Y[i]: 470868309 Y[j]: -816049599 //Something is wrong here
temp: -2089704922

这段代码可能不是练习的好解决方案,我需要对其进行改进,但我仍然无法弄清楚为什么该值为负数。

请帮忙。

谢谢。

代码:

int main()
{

int N;
int X[100000];
int Y[100000];

cin >> N; cin.ignore();
for (int i = 0; i < N; i++) { //reading all input

cin >> X[i] >> Y[i]; cin.ignore();
}

int ilgis=0; //ilgis means length

for(int i=0; i<N-1; i++){ //"min" is set to a very high value
//so it could find a lower value later
// "not the best solution"

int min=99999999999999999999; //shortest distance between houses
for(int j=0; j<N; j++){ // here I am trying to find the shortest
// distance from one house to another

if(j!=i){ //I can't count distance from the same house because
// it would be 0

int temp=0;
//counting the distance differently if the
//value is negative or positive

if(X[i]<=0&&X[j]<=0) temp+=abs(abs(X[i])-abs(X[j]));
else if(X[i]<=0&&X[j]>=0) temp+=abs(X[i])+abs(X[j]);
else if(X[i]>=0&&X[j]>=0) temp+=abs(X[i]-X[j]);
else if(X[i]>=0&&X[j]<=0) temp+=(X[i])+abs(X[j]);

//same with y axis

if(Y[i]<=0&&Y[j]<=0) temp+=abs(abs(Y[i])-abs(Y[j]));
else if(Y[i]<=0&&Y[j]>=0) temp+=abs(Y[i])+abs(Y[j]);
else if(Y[i]>=0&&Y[j]>=0) temp+=abs(Y[i]-Y[j]);
else if(Y[i]>=0&&Y[j]<=0) temp+=(Y[i])+abs(Y[j]);

if(min>temp) min=temp;
}
} //if i found the shortesst distance between
//houses I add that value to overall distance
// and continue until all houses are checked
ilgis+=min;

}
cout<<ilgis<<endl;
}

练习的输入:

 8
-28189131 593661218
102460950 1038903636
938059973 -816049599
-334087877 -290840615
842560881 -116496866
-416604701 690825290
19715507 470868309
846505116 -694479954

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com