DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

Intersecction Of Two Lines In C

07.01.2005
| 2359 views |
  • submit to reddit
        
//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

#include <stdio.h>

typedef struct {
        float x1, x2, y1, y2;
} Segmento;

typedef struct {
	float x, coefLinear;
} EquacaoDaReta;

void preencherSegmento( Segmento *s ){
    printf( "Entre com as coordenadas do segmento A no formato: x1,y1,x2,y2:" );
    scanf( "%f,%f,%f,%f", &s->x1, &s->y1, &s->x2, &s->y2 );
}

float calcularTangente( Segmento *s ){
	return tangenteInvalida( s ) ? 0 : ( s->y1 - s->y2 ) / ( s->x1 - s->x2 );
}

int tangenteInvalida( Segmento *s ){
	return !( s->x1 - s->x2 );
}

int main( int argc, char *argv[] ){
    Segmento segA, segB;
	EquacaoDaReta eqA, eqB;
 	float tangenteA, tangenteB;
	float interseccaoX, interseccaoY;

	preencherSegmento( &segA );
	preencherSegmento( &segB );

    tangenteA = calcularTangente( &segA );
	tangenteB = calcularTangente( &segB );

	if( tangenteInvalida( &segA ) && tangenteInvalida( &segB ) ){
		printf( "As retas sao paralelas, portanto nunca se cruzam.");
		system( "pause" );
		return 0;
	}
	else if( tangenteInvalida( &segA ) ){
  		interseccaoX = segA.x1;
		interseccaoY = segB.y1 + tangenteB * ( segA.x1 - segB.x1 );
	}
	else if( tangenteInvalida( &segB ) ){
		interseccaoX = segB.x1;
		interseccaoY = segA.y1 + tangenteA * ( segB.x1 - segA.x1 );
	}
	else if( tangenteA == tangenteB ){
		printf( "As retas sao paralelas, portanto nunca se cruzam.");
		system( "pause" );
		return 0;
	} else {
		eqA.x = tangenteA;
		eqA.coefLinear = tangenteA * -segA.x1 + segA.y1;

		eqB.x = tangenteB;
		eqB.coefLinear = tangenteB * -segB.x1 + segB.y1;

	    interseccaoX = ( eqB.coefLinear - eqA.coefLinear ) / ( eqA.x - eqB.x );
		interseccaoY = eqA.x * interseccaoX + eqA.coefLinear;
	}

	printf( "\nO ponto de interseccao eh: (%f, %f )", interseccaoX, interseccaoY );
	system( "pause" );
	return 0;

}