Hello, OnlineGDB Q&A section lets you put your programming query to fellow community users. Asking a solution for whole assignment is strictly not allowed. You may ask for help where you are stuck. Try to add as much information as possible so that fellow users can know about your problem statement easily.

how to do a simple division

+6 votes
asked Aug 19, 2023 by Edoardo Festante (250 points)
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;
}

6 Answers

+1 vote
answered Aug 27, 2023 by Peter Minarik (86,580 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 Ramanathan (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 Murthu Lucky (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;
    
}
0 votes
answered Sep 8, 2023 by Edoardo Festante (250 points)
Thanks at all for the help

E
0 votes
answered Sep 8, 2023 by Praveen kumar Madan (190 points)
#include <stdio.h>

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

    return 0;
}

You can simply use Type Conversion
0 votes
answered Nov 7, 2023 by Gulshan Negi (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 

Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...