Doubt in C code!

1

Someone could help me with this issue from my exercise list:

Make a program that receives a real number, find and show:

  • a) the whole part of that number;
  • b) the fractional part of that number;
  • c) the rounding of that number.

I do not know how to calculate this, my teacher had to use modf , but it did not work, giving a web search I found the following code that when tested it ran perfectly, but I can not understand the logic that was used.

float numero,inteira,fracao,arred;
printf("Digite um numero real: ");
scanf("%f%*c",&numero);
printf("Parte Inteira : %d \n",(int) numero);
printf("Parte Decimal : %f", numero - ((int)numero));
    
asked by anonymous 22.03.2018 / 23:36

1 answer

1
Putting (int) before a variable returns only the whole part of the number (without rounding it), so in the second print it showed only the whole part, so I explained, in the third printf subtracted only the whole part of the floating-point number, leaving only the decimal part, and for the fourth printf that would be relative to rounding you could use the round (variavelFloat) function, which rounds the variable.

The code looks like this:

{
    float numero,inteira,fracao,arred;
    printf("Digite um numero real: ");
    scanf("%f%*c",&numero);
    printf("Parte Inteira : %d \n",(int) numero);
    printf("Parte Decimal : %f", numero - ((int)numero));
    printf("Arredondado : %d", (int)round(numero));
}
    
22.03.2018 / 23:47