Doubt in code in C!

Asked

Viewed 591 times

1

Personal someone could help me in this matter of my exercise list:

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

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

I do not know how I calculate this, my teacher ordered to use the modf, but it didn’t work, giving a web search I found the following code that when testing it ran perfectly, but I can’t 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));
  • 1

    C is not C# and is not C++.

  • the question is about how to do or what the algorithm you found does?

  • How to do,I did not understand how the code works

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 number with floating point, leaving only the decimal part, and for the fourth printf that would be relative to rounding you could use the round function (variavelFloat), which rounds the variable.

The code would look 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));
}
  • 1

    That’s what I didn’t understand, thank you very much man you saved me kk

  • 1

    floor won’t round up the number the way you want it. floor will truncate the number. It’s the operation piso of mathematics: will round to the lowest integer

  • 3

    @Jeffersonquesado there are controversies :) There are different ways to make the floor . Sure, you’ll always take the floor, but the definition of what the floor is can change.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.