Adan
Adan

Reputation: 65

C# How to subtract list numbers into a variable until it reaches x <= 0?

This program is trying to subtract the contents of the list to the variable 'health', imagine the value of health being the amount of life force in an object, each number in the list is a damaging force, im trying to get the index in which health <= 0. For example, health - theOneList[0] = 2 - 1.1 = .9, since .9 != <=0, keep subtracting.

    var wqat = 1.1;
    var rat = .2;
    var eat = .8;
    var baat = 1.2;

    var health = 2;


    List<double> theOneList = new List<double>();
    List<double> theOneList = new List<double>();

    theOneList.Add(wqat);
    theOneList.Add(rat);
    theOneList.Add(eat);
    theOneList.Add(baat);




    for (int i = 0; i < 4; i++)
    {
        test.Add(health - theOneList[i]);

        Console.WriteLine(test[i]);
    }

Upvotes: 0

Views: 2613

Answers (3)

Hari Prasad
Hari Prasad

Reputation: 16956

Another simple way would be having Linq statement.

var heathRemaining = theOneList.TakeWhile(c=> (health-=c) >=0.0);

Working fiddler Demo

Upvotes: 2

Rana
Rana

Reputation: 1755

Use a while loop instead:

int i = 0;
while(health > 0 && i < theOneList.length){
   // keep subtracting
   test.add(health - theOneList[i]);
   Console.WriteLine(test[i]);
   i++;
}

Upvotes: 0

Bradford Dillon
Bradford Dillon

Reputation: 1800

You could do this with a simple condition in your for loop.

int i = 0;

for(i = 0; i < theoneList.Length && health > 0; i++)
{
    health -= theOneList[i];
}

Console.WriteLine(i);

First off, you don't really want to hard code your iterator upper value. Using .Length in your loop condition makes it such that you will iterate over the full list.

The way this works is that it will keep subtracting the values from the list from health until health is not greater than zero. This will break the loop leaving the location of the value that brought health below zero as the value of i.

Also, if all you care about is what value in your list brought the health to 0 or less, then there is no need to push the health values back in to the list.

Upvotes: 0

Related Questions