简体   繁体   中英

Average of textfields depending on how many textfield are “used”

Little explication: I have an app with 5 textfields, i already got the code to make the avaerage of them. Using floates and giving a variable to each textfield.so, the adding of the value of all the textfield /5 (divided per 5)

My problem is that when a textfield is leaved emptty, its not goona be /5, if user fill in only 4 cells it will be/4 and so on.

Question: how to divide the adding of cells depending in how many cells have content?

I was tryng with textfield.text.length > 0 in an if. But i dont get it

Thanks, hope i was clear.

You could check each textfield and see if the text is NULL or blank (@"")

Use an int to keep track of the number of textfields that have a value.

For example:

int counter = 0;
float total = 0.0;

if([textfield1.text length] > 0)
{
    counter++;
    float thisValue = [textfield1.text floatValue];
    total = total + thisValue;
}

repeat this for all 5 textfields and then divide your total by the counter variable. You could include the if statement in a loop if you are going to vary the number of text fields or to reduce the amount of coding you do.

EDIT I have changed my answer based on the good suggestions of other to use text.length

try to count the number of used textfields by increasing a number every time you read out a textfield that has valid text in it and divide the result by that number. (logically the "number" should be initialized as 0)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM