# how to do a simple division

Hello to all.

the result of this code "C" is 0.000000 but is wrong, the correct results is 0.500000.

can someone help me to understand the error?

thank you,

E

#include <stdio.h>

int main()
{
float a;
a=1/2;
printf("%f",a);

return 0;
}

+1 vote
answered Aug 27, 2023 by (88,520 points)
`float a = 1 / 2;`

This means, that let's create a variable called a with the type float and set the value to be 1 / 2;

`1 / 2`

means let's divide the integral number 1 by the integral number 2. This is an integral division (resulting in an integral number) so the result is 0.

Then this zero is set to be the value of a, which involves an int to float conversion (casting).

What you want here is a float division, to begin with. You can tell your compiler that you are using floating point literals, not integral literals by the f suffix:

`float a = 1.0f / 2.0f;`

If you do not add the f suffix the code will still do what you'd expect it to do, but it will do a double division as floating point literals without the f suffix default to double type, not float.

I hope this makes more sense now.

+1 vote
answered Sep 4, 2023 by (160 points)
hey bro ,you could try this method

float a=1.0 / 2 ;(or) a=1 / 2.0  ;
+1 vote
answered Sep 8, 2023 by (160 points)
#include<stdio.h>
int main() {
float a,b,c;
printf("enter the two no : ");
scanf("%f %f",&a,&b);
c=a/b;
printf("%f",c);
return 0;

}
answered Sep 8, 2023 by (250 points)
Thanks at all for the help

E
answered Sep 8, 2023 by (190 points)
#include <stdio.h>

int main()
{
float a;
a=(float)1/2;
printf("%f",a);

return 0;
}

You can simply use Type Conversion
answered Nov 7, 2023 by (1,580 points)

Can you try the below code, hope you can get the result you are looking for.

#include <stdio.h>

int main() {
float a;
a = 1.0 / 2;  // or a = 1 / 2.0 or a = 1.0 / 2.0
printf("%f", a);

return 0;
}

Thanks