samedi 28 mars 2015

Calculate two numbers and skip the sign?

I have the following situation: I calculate two values on the one side and two other values on the other side. Then I compare the two results, but in this comparison the sign doesn't matter for me. For example:


(1 - 2) == (2 - 1) - should tell me, that 1 == 1, not that -1 != 1


I can solve this by writing a function that gives me an absolute value back from the calculation, but maybe someone knows a better way.


For a better understanding I enclose my code, the important part is in the third if-statement:



#include <stdio.h>
#include <stdbool.h>
#define N 8

int abs(int x){
if (x<0)
return -x;
return x;
}

bool gefahr(bool queen[N][N]){

int dame1x=N+1;
int dame1y=N+1;
int dame2x=N+1;
int dame2y=N+1;

for(int i=0; i<N;i++){
for(int j=0;j<N;j++){
if(queen[i][j] && dame1x>N){
dame1x=i;
dame1y=j;
} else if(queen[i][j] && dame2x>N) {
dame2x=i;
dame2y=j;
}
}
}

printf("Dame 1: %d %d\n",dame1x,dame1y);
printf("Dame 2: %d %d\n",dame2x,dame2y);

if(dame1x==dame2x){
printf("Waagerecht bedroht\n");
return true;
}
if(dame1y==dame2y){
printf("Senkrecht bedroht\n");
return true;
}

if(abs(dame2x-dame1x)==abs(dame2y-dame1y)){
printf("Diagonal bedroht\n");
return true;
}
}

int main(){

bool feld[N][N];

for(int i=0; i<N;i++){
for(int j=0;j<N;j++){
feld[i][j]=false;
}
}
feld[0][4]=true;
feld[4][4]=true;
gefahr(feld);
feld[0][4]=false;
feld[4][4]=false;

feld[2][2]=true;
feld[0][4]=true;
gefahr(feld);
feld[0][4]=false;
feld[4][4]=false;

feld[0][4]=true;
feld[4][4]=true;
gefahr(feld);

}


Thanks for your help!


Jan


Aucun commentaire:

Enregistrer un commentaire