0

I am solving the hacker rank problem plus minus and encountered the problem where the division gives 0.0000

int main()
{
    int array_size;
    printf("Enter the size of array: \n");
    scanf("%d",&array_size);

    int array [array_size];
    for(int i=0;i<array_size;i++)
    {
        scanf("%d",&array[i]);
    }

    int positive=0;
    int negative=0;
    int zero=0;
    for(int i =0; i<array_size;i++)
    {
        if(array[i]<0)
        {
            negative++;
        }
        if(array[i]>0)
        {
            positive++;
        }
        if(array[i]=0)
        {
            zero++;
        }
    }
    float x = positive / array_size;
    float y = negative / array_size;
    float z = zero / array_size;
    printf("%lf \n",x);
    printf("%lf \n",y);
    printf("%lf \n",z);

    return 1;

}

Actual Result:- 0.00000000 0.00000000 0.00000000

Expected Result:- The actual divisions...

Janit Lodha
  • 1
  • 1
  • 1

1 Answers1

0

You need to cast to float. Otherwise the arithmetic conversions will convert only the integer result to float.

float x = positive / array_size

You want

float x = (float) positive / array_size

The full algorithm of conversions is presented in ISO 9899, chapter 6.3.1.8 Usual arithmetic conversions

alinsoar
  • 14,813
  • 4
  • 53
  • 68
  • Thank you sir, it worked! But can you please elaborate the explanation? I am not able to understand what you meant by "Otherwise the arithmetic conversions will convert only the integer result to float.". – Janit Lodha Jun 13 '19 at 13:26
  • @JanitLodha completed – alinsoar Jun 13 '19 at 13:30