Using float for division in C language
Je voudrais diviser deux int pour avoir un float. Mais dans mon programme, ça ne fonctionne pas il m'affiche 1.000000. Est-ce en raison de mon void modification(int * a ) ?
Mon programme :
Mon programme :
1 #include <stdio.h> 2 void modification(int * a ) 3 4 { 5 *a=15; 6 } 7 int main() 8 { 9 int a = 15; 10 int b = 23; 11 float f; 12 printf("%d\n",b); 13 modification(&b); 14 f = (float)b / a; 15 printf("%f \n",f) ; 16 17 return 0; 18 19 } 20</stdio.h>
3 answers
-
ContributorHi Ruvox,
Try this:
f = (float) b / a;
If you don't cast one of the values to thefloat
type, you're performing a division of two integer types, and the C language will then understand that you want to perform an integer division and will naturally give you a result that truncates the decimals.
As long as one of the operands of the division is of afloat
ordouble
type, depending on the type of result you want, C will perform a division with decimals.
Dal