Rounding in C

Asked

Viewed 27,217 times

6

I wonder how I could ignore rounding in divisions, for example:

4/3 = 1,33... ~ 1 | 5/3 = 1,66... ~ 2

Right?

I wanted to make a program in C, that in these cases, the rounding is not done, because the idea is to increase a number if it contains decimals, regardless if the decimal number (doubtful number) is greater, less than or equal to 5. Any idea?

Code:

void main() {

  float n1 = 4.0;
  float n2 = 3.0;

  float result;

  result = n1 / n2; // res = 1,33 ~ 1

  // Aqui eu quero que o resultado seja 2
  printf("Resultado incrementado: %d\n", result);

  n1 = 5;
  result = n1 / n2; // res = 1,66 ~ 2

  // Aqui eu quero que o resultado seja 2
  printf("Resultado incrementado: %d\n", result);

}

In the first printf I need to increment to get the desired result, in the second no. That is, it uses the rules of rounding. What I want is that if there are decimals in the number, that it is incremented and not decremented.

  • 1

    Show us what you’ve done to make us understand what’s wrong.

  • I put an example

  • Voce knows that since its "result" is a variable of type "int", it will never connect the decimal parts, no?

1 answer

12


The library (Math.h) until 2010 did not implement the function round() by nature, there were only two functions that did this through mathematical concepts.

floor()

Implements the floor concept. Briefly, it is the first integer found smaller than the result value of the operation

Examples:

  • floor(1.3) // retorna 1
  • floor(2.9) // retorna 2

Ceil()

Implements the roof concept. Briefly, it is the first integer found larger than the result value of the operation

Examples:

  • ceil(1.1) // retorna 2
  • ceil(3.6) // retorna 4

In 2011 the function was implemented round() to the library math.h.

round()

Returns the nearest integer to the number passed as argument.

Examples:

  • round(1.4) //retorna 1
  • round(3.6) //retorna 4

It is possible to make your own implementation for the function round() if you do not want to include the library in your project.

Implementation

I usually add this function while avoiding an extra library:

int round(double number)
{
    return (number >= 0) ? (int)(number + 0.5) : (int)(number - 0.5);
}

Where 0.5 is added/subtracted to the number, and the same truncated to integer, resulting in a perfect implementation of round()

source: http://www.codeproject.com/Articles/58289/C-Round-Function

  • Adding a little theory: https://pt.wikipedia.org/wiki/Parte_integer

  • 1

    Thanks, the Ceil(double *) function solved my problem!!!

Browser other questions tagged

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