Question:
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, which in these cases, rounding is not done, as the idea is to increment a number if it contains decimals, regardless of whether the decimal number (doubtful 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 printf
I need to increment to get the desired result, in the second I don't. That is, it uses the rounding rules. What I want is that if there are decimals in the number, it should be incremented and not decremented.
Answer:
The library (math.h) until 2010 did not implement the round()
function by nature, there were only two functions that did this through mathematical concepts.
floor()
Implements the concept of floor. Briefly, it is the first integer found less 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, it 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 in the math.h
library.
round()
Returns the closest integer to the number passed as an argument.
Examples:
-
round(1.4) //retorna 1
-
round(3.6) //retorna 4
You can make your own implementation for the round()
function if you don't want to include the library in 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/subtracted to the number, and the same truncated to integer, resulting in a perfect round()
source: http://www.codeproject.com/Articles/58289/C-Round-Function