Rounding in C

6

I would like to know 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, rounding is not done, because the idea is to increment a number if it contains decimals, regardless of whether the decimal number is greater, less than or equal to 5 Any ideas?

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% w / o of%, I need to increment to get the desired result, the second does not. That is, it uses the rules of rounding. What I want is that if there are decimals in the number, it is incremented and not decremented.

    
asked by Vynstus 20.07.2015 в 15:42
source

1 answer

10

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

floor ()

Implements the floor concept. Briefly 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 concept of ceiling. Briefly is the first integer found greater than the result value of the operation

Examples:

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

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

round ()

Returns the integer closest to the number passed as an argument.

Examples:

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

You can do your own implementation for the round() function if you do not want to include the library to your project.

Implementation

I usually add this function, avoiding an extra library:

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

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

source: link

    
answered by 20.07.2015 / 15:59
source