Rounding off happens even though I declared my variables as float in python

Viewed 37

I have to count pos,neg and 0 vals and divide them by array size and return the three values with 6 decimal places. Here is the array 6 -4 3 -9 0 4 1

i tried converting the variables to float and at every stage i used the float function

def plusMinus(arr):
    a=float(0.000000);
    b=float(0.000000);
    c=float(0.000000);
    for i in arr:
        if i==0:
            a=a+float(1.000000);
        elif i<0:
            b=b+float(1.000000);
        else:
            c=c+float(1.000000);
    a=a/(float(len(arr))-float(1));
    b=b/(float(len(arr))-float(1));
    c=c/(float(len(arr))-float(1));
    print ("{0:.6f}".format(c));
    print ("{0:.6f}".format(b));
    print ("{0:.6f}".format(a));
if __name__ == '__main__':
    n = int(input())

    arr = list(map(int, input().rstrip().split()))

    plusMinus(arr)

expected output:- 0.500000 0.333333 0.166667

my output:- 0.600000 0.400000 0.200000

1 Answers

You dont need to declare your values as floats, just allow python do handle the values:

def plusMinus(arr):
    pos = 0
    neg = 0
    zer = 0

    for n in arr:
        if n > 0:
            pos += 1
        elif n < 0:
            neg += 1
        else:
            zer += 1

    print(format(pos / len(arr), '.6f'))
    print(format(neg / len(arr), '.6f'))
    print(format(zer / len(arr), '.6f'))
Related