-2

I have c# program that calculates percentage and returns int value, but it always returns 0.

I have been writing code for 16 constitutive hours so I appreciate if you find the mistakes within it.

I debugged my code and I found that the value is being passed correctly.

private int returnFlag(int carCapacity, int subscribers)
{
    int percentage = (subscribers / carCapacity)*100;
    return percentage;
}
abelenky
  • 63,815
  • 23
  • 109
  • 159
Jim
  • 117
  • 2
  • 12

3 Answers3

5

What you're seeing is the result of operating on two integers, and losing the fractional portion.

This piece of code, when using the values 5 and 14, will truncate to 0:

(subscribers / carCapacity)

You need to cast one of the operands to a double or decimal:

private int returnFlag(int carCapacity, int subscribers)
{
    decimal percentage = ((decimal)subscribers / carCapacity) * 100;

    return (int)percentage;
}
rbsdca
  • 139
  • 1
  • 8
Grant Winney
  • 65,241
  • 13
  • 115
  • 165
3

The issue is that since you're performing math on int (read: integer) values, any fractions or remainders get thrown out. This can be seen by changing your code to

int percentage = (subscribers / carCapacity);
percentage *= 100;

Since (subscribers / carCapacity) results in less than one, the only possible number an int can hold is 0 - and 0 * 100 is 0.

You can fix this by converting to a more precise number, such as double, before performing operations:

private int returnFlag(int carCapacity, int subscribers)
{
    double percentage = ((double)subscribers / (double)carCapacity) * 100.0;
    return (int)percentage;
}
David
  • 10,458
  • 1
  • 28
  • 40
1

Integer types (int) don't work with fractions. Change the types you are working with in your division to decimal, double, single, or float.

Russ
  • 4,091
  • 21
  • 32