Reputation: 9
Been trying to get the outputs to give me the number without rounding, not sure what I'm missing
float NumberOfTrees1;
for (NumberOfTrees1 = 1000.0; NumberOfTrees1 >= 50; NumberOfYears++)
{
NumberOfTrees1 = NumberOfTrees1 - (NumberOfTrees1 * 0.13);
printf("Number of Remaining Trees: %0.1f\n",NumberOfTrees1);
}
My Output:
Number of Remaining Trees: 61.7
Number of Remaining Trees: 53.7
Number of Remaining Trees: 46.7
Required Output:
Number of Remaining Trees: 61
Number of Remaining Trees: 53
Number of Remaining Trees: 46
I understand that the %0.1f
is what gives me the .7
but when I use %0.0f
it rounds up my numbers which I don't want. Been switching things around from using int
, double
, long float
etc to no avail.
Any help would be great and thank you in advance!!!
Upvotes: 0
Views: 848
Reputation: 11259
You can cast into int
in order to truncate your number:
int main(void) {
double d = 53.7;
float f = 46.7f;
int a = (int)d;
int b = (int)f;
printf("%d %d\n", a, b);
}
output:
53 46
Or, as suggested by @user3386109, you may use floor(), but you will need to also include <math.h> header and compile with -lm
Upvotes: 0
Reputation: 1420
Antonin GAVRELs answer should print the desired output, but if you don't want to cast the floating point numbers into integers, you could use the double floor (double x)
function from <math.h>
.
#include <math.h>
#include <stdio.h>
int main(void)
{
double x = 53.7;
double floored = floor(x);
printf("⌊%0.1lf⌋ = %0.1lf\n", x, floored);
return 0;
}
The program can be compiled with -lm
and prints the following when executed:
⌊53.7⌋ = 53.0
Upvotes: 1