convert float to integer
I want
12.345-->12
23.468-->23
i am newbie, i can do it by nearest integer y = floor(x+0.5);
but want to learn by other way,
1 2 3 4 5 6 7
|
#include <stdio.h>
int main(){
float f = 12.345;
int i = (int)f;
printf(int i);
return 0;
}
|
prompt
In function ‘int main()’:
error: expected ‘)’ before ‘int’
the most simply way to convert from float to integer (with rounding) is:
1 2
|
float f = 12.345;
int i = int(f + 0.5);
|
floor()
and
ceil()
are somewhat cumbersome for that purpose
line 5 should be e.g.:
printf("%d\n", i);
EDIT: Disregard. Yes forgot about negatives: look at Grey Wolf post
Last edited on
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27
|
#include <stdio.h>
#include <math.h>
int main()
{
float aFloat = -12.545f;
int anInt = (int) floor(aFloat + 0.5);
int anotherInt = (int) (aFloat + 0.5);
printf("Floor: %d and Cast: %d\n",anInt, anotherInt);
// You have to take care with negative numbers
int yetAnotherInt = 0;
if (aFloat >= 0)
yetAnotherInt = (int) (aFloat + 0.5);
else
yetAnotherInt = (int) (aFloat - 0.5);
//
// Can also be done as
// int yetAnotherInt = (aFloat >= 0) ? (int)(aFloat + 0.5) : (int)(aFloat - 0.5);
printf("Floor: %d and Cast: %d\n",anInt, yetAnotherInt);
return 0;
}
|
Floor: -13 and Cast: -12
Floor: -13 and Cast: -13
Press any key to continue . . . |
Last edited on
Many thanks!
It is really a good place to learn C++.
I have spent 2 days on this question.
Topic archived. No new replies allowed.