Search code examples
for-loopcastingoutput

How to Determine How many cycles it would take to get a given value to 0 by decreasing it by a given amount


This is my problem, i need to take double onHand and reduce it by the double consume, then determine how many cycles it would take to reach 0. then use Math.Round 3 to round it to 3 decimal points.

        public static int Test4(double onHand, double consume)
        {
            int answer = 1;
            for (int i = (int)(consume); i > onHand; i--)
            {
                answer -= (int)onHand;
            }
            return answer;
        }

I tried creating multiple variables like introducing decimals, casting the doubles into floats and ints but i can only get to the point where my answer outputs the int of the onHand.


Solution

  • You just have to make a division.

    Assuming onHand is 3.02 and consume is 0.24, you divide them like onHand / consume and that will result in 12.583333. You will have to ceil or round-up the value (13). That is the number of times it'll go trough the loop to reach or pass 0.

    Example

    public static int Test4(double onHand, double consume)
    {
        double answer = (decimal)onHand / (decimal)consume;
        return (int) Math.Ceiling(answer);
    }
    

    I'm no expert on C# so I don't know if the casting is neccesary.