0

I've written a code for the following program but the output seems to be wrong. Question: https://www.hackerrank.com/challenges/plus-minus

Code:

#include <stdio.h>
int main() {

     int N,num,i,cp=0,cn=0,cz=0;
     double fp,fn,fz;
     scanf("%d",&N);
     for(i=0;i<N;i++)
     {
         scanf("%d",&num);
         if(num>0)
            cp=cp+1;
        else if(num==0)
            cz=cz+1;
        else
            cn=cn+1;
    }
    fp=cp/N;
    fn=cn/N;
    fz=cz/N;
    printf("%lf\n%lf\n%lf",fp,fn,fz);
    return 0;
}

The Output comes as:

0.000000
0.000000
0.000000
Varshini
  • 187
  • 1
  • 6
  • 20

3 Answers3

0

For correct result cast these expression's to double-

                     like this
fp=cp/N;         //  fp=(double)cp/N;
fn=cn/N;         //  fn=(double)cn/N;
fz=cz/N;         //  fz=(double)cz/N;

Working code

In previous case if cp(or cn or cz) is less than N then due to integer division you will get 0(fraction part will be discarded). Therefore m these casts .

Another method would be to use all variables as double .

ameyCU
  • 16,489
  • 2
  • 26
  • 41
0

you are doing an integer division which creates only integer results. If you want to calculate floating point results you need to perform floating point divisions.

int a = 1;
int b = 3;
int c = a / b;

// c is now 0 -> integer division

double i = 1.0;
double j = 3.0;
double k = i / j;

// k is now 0.3333333 -> floating point division

codencandy
  • 1,701
  • 1
  • 10
  • 20
0

Istructions:

fp=cp/N;
fn=cn/N;
fz=cz/N;

Are performed as integer division.

Change your code to:

 fp=(double)(cp)/(double)(N);
 fn=(double)(cn)/(double)(N);
 fz=(double)(cz)/(double)(N);
LPs
  • 16,045
  • 8
  • 30
  • 61
  • 1
    No point in casting both sides of the division, very verbose code. – unwind Sep 24 '15 at 09:36
  • @unwind I chose to be verbose in this case to give OP indication that there are integers on both side of formula. – LPs Sep 24 '15 at 09:46