segunda-feira, 10 de novembro de 2014

Casting de tipos em C

Algumas vêzes criando um programa em linguagem C, precisamos declarar um vetor
obrigatoriamente em um determinado tipo, más ocorre, que durante o programa,
queremos aproveitar partes deste mesmo vetor em outros tipos.
Neste código simples mostro como isto pode ser feito, basta usar um "Type Casting".
Proprositamente na primeira impressão do vetor imprimimos a parte decimal, e na segunda
imprimimos a parte inteira do mesmo vetor, já transformada em inteiro pelo casting.

Ótimo código indicado a iniciantes em C:

veja abaixo imagens do programa em execução:



Veja abaixo o código do programa:

#include <stdio.h>
#include <conio.h>
void Janela5(){system("Color F0");
int lin, col;
for ( lin = 0; lin <= 25; lin++ ){
    for ( col = 0; col <= 80; col++ ){
        gotoxy( col, lin );
        if ( lin == 2 ){textbackground(LIGHTBLUE);printf( " ");}
        if ( col == 1 ){textbackground(LIGHTBLUE);printf(" ");}
        if ( lin == 25 ){textbackground(LIGHTBLUE);}
        if ( col == 80 ){textbackground(LIGHTBLUE);printf(" ");}
    }
}textbackground( BLACK );
}
void inicio(){system ("title CASTING DE TIPOS EM C");
system("cls");
int i;do{Janela5();textbackground(WHITE);
textcolor(LIGHTRED);gotoxy(33,7);printf("CASTING DE TIPOS EM C");
textcolor(BROWN);gotoxy(25,10);printf("Programa desenvolvido por:");
textcolor(BLACK);gotoxy(52,10);printf("Samuel Lima");
textcolor(BLUE);gotoxy(34,12);printf("sa_sp10@hotmail.com");
textcolor(LIGHTBLUE);gotoxy(24,14);printf("DIGITE    PARA SAIR OU   PARA CONTINUAR  ");
textcolor(LIGHTRED);gotoxy(32,14);printf("1");textcolor(LIGHTRED);gotoxy(47,14);printf("2");
gotoxy(41,16);
scanf("%d",&i);fflush(stdin);
if( i == 1 ){textcolor(LIGHTRED);gotoxy(35,20);printf ("MUITO OBRIGADO");Sleep(1800);exit(0);}
if( i == 2 ){system("cls"); return;}
else {textcolor(LIGHTRED);gotoxy(37,20);printf ("\aOPÇÃO ERRADA");Sleep(1800);system("cls");}
}
while(i);
}
int main(){
    inicio();Janela5();textbackground(WHITE);
    float Temp [ ] [ 16 ] =
    { { 8.9 }, { 9.5 }, { 10 }, { 11.8 }, { 12.7 }, { 13.6 }, { 14.3 }, { 15.4 },
            { 1 }, { 2 }, { 3 }, { 4 }, { 5 }, { 6 }, { 7 }, { 8 } };
    int i;int Vet [ 8 ];
    textcolor(LIGHTRED);gotoxy(33,3);printf("CASTING DE TIPOS EM C");
    textcolor(LIGHTBLUE);gotoxy(24,5);printf("Imprimindo abaixo a parte decimal do vetor");
    gotoxy(24,7);textcolor(LIGHTRED);
    for( i = 0; i < 8; i++ ){
        printf(" %.1f ", Temp [ i ] [ 0 ] );
    }getchar();
    textcolor(LIGHTBLUE);gotoxy(24,9);printf("Imprimindo abaixo a parte inteira do vetor");
    gotoxy(24,11);textcolor(LIGHTRED);
    for( i = 8; i < 16; i++ ){
        *Vet = ( int ) Temp [ i ] [ 0 ];//Transforma o vetor float em int
        printf(" %d ", *Vet );
    }
    Sleep(1800);textcolor(LIGHTRED);gotoxy(35,18);printf ("MUITO OBRIGADO");
    getchar();
    return(0);
}