Reputation: 163
fun plusMinus(arr: Array<Int>): Unit {
var counterPositive = 0
var counterNegative = 0
var counterZero = 0
for(i in 0 until arr.size) {
if(arr[i] > 0) {
counterPositive++
} else if(arr[i] < 0) {
counterNegative++
} else {
counterZero++
}
}
println(counterPositive)
println(arr.size)
val a = counterPositive/arr.size
println(a)
}
I try to solve simple algorithm question, but I face this interesting thing. So, i try to find positive, negative numbers, and zeros in array. And each one divide to size of array. And print it But i get 0 as result. But when i debug code i see that counterPositive is for example 4 and arr.size for example 5 but i get 0. Why?
Upvotes: 0
Views: 560
Reputation: 16224
You get zero since counterPositive
, counterNegative
and counterZero
are initialized with 0
so the type Int
is inferred.
Since the array size is an Int
, the division between two Int
results in an Int
.
To fix it, you'd need to use a Float
or a Double
.
val a = counterPositive.toFloat() / arr.size
Upvotes: 5