How to divide 2 int in c?

后端 未结 5 2062
清酒与你
清酒与你 2020-12-10 18:29

wanna divide 2 numbers and get the result like this:

5 / 2 = 2.50

But it only outputs 2.

I don\'t now what i\'m doing wrong.

Here my code:

相关标签:
5条回答
  • 2020-12-10 18:37

    You have to use float or double variables, not int (integer) ones. Also note that a division between two integers will lead to an integer result, meanwhile a division between a float/double and an integer will lead to a float result. That's because C implicitly promote this integer to float.

    For example:

    5/2 = 2
    5/2.0f = 2.5f
    

    Note the .0f, this actually means that we are dividing with a float.

    0 讨论(0)
  • 2020-12-10 18:40

    To avoid the typecast in float you can directly use scanf with %f flag.

    float a;
    float b;
    float c;
    printf("First number\n");
    scanf("%f", &a);
    printf("Second number\n");
    scanf("%f", &b);
    c = a / b;
    printf("%f", c);
    
    0 讨论(0)
  • 2020-12-10 18:42

    The '/' - sign is for division. Whenever in C language, you divide an integer with an integer and store the data in an integer, the answer as output is an integer. For example

    int a = 3, b = 2, c = 0;
    c = a/b; // That is c = 3/2;
    printf("%d", c);
    

    The output received is: 1
    The reason is the type of variable you have used, i.e. integer (int)
    Whenever an integer is used for storing the output, the result will be stored as integer and not a decimal value.

    For storing the decimal results, C language provide float, double, long float and long double.

    Whenever you perform an operation and desires an output in decimal, then you can use the above mentioned datatypes for your resultant storage variable. For example

    int a = 3, b = 2;
    float c = 0.0;
    c = (float)a/b; // That is c = 3/2;
    printf("%.1f", c);
    

    The output received: 1.5
    So, I think this will help you to understand the concept.
    Remember: When you are using float then the access specifier is %f. You need to convert your answer into float, just as I did, and then the answer will be reflected.

    0 讨论(0)
  • 2020-12-10 18:47

    In C, only an int type number is displayed. 5/2 gives a floating point type number. So, the compiler compiles it only with the integer value.

    0 讨论(0)
  • 2020-12-10 18:54

    You need a double variable to store the result. int stores only integers. Additionally, you have to typecast the other variables also before performing the division.


    Do something like this

    double c;
    .
    .
    .
    c = (double)a / (double)b;
    printf("%f", c);
    

    NOTE:

    You do not need the & in printf() statements.

    0 讨论(0)
提交回复
热议问题