Function help

So I'm trying to write a program that calculates the sizes of clothing. Right now, I want to make it so that every 10 years after the age of 30, someone's jacket size goes up by 1/8th of an inch, but I want to do it without having too many "if" statements. Is there a way to do it so that the program checks the user's age and adds the measurement accordingly, rather than having a slew of "if / else if" statements like the code that's shown here? I'm getting the information from a file, if that helps. Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
  void jacketSize(float height[], float weight[], float age[]){
	float jacket[10];
	int i;

	for (i = 0; i < 10; i++){
		if (age[i] >= 40){
			jacket[i] = ((height[i] + 0.125) * weight[i]) / 288;
		}
		else if (age[i] >= 50){
			jacket[i] = ((height[i] + 0.250) * weight[i]) / 288;
		}
		else if (age[i] >= 60){
			jacket[i] = ((height[i] + 0.375) * weight[i]) / 288;
		}
		else if (age[i] >= 70){
			jacket[i] = ((height[i] + 0.5) * weight[i]) / 288;
		}
	}

	return;
}
You could do this very sleekly by using a bit of maths. If you took 30 away from the age they entered and then rounded it down, this would get the decade of the age. By further dividing this by 10 you can get the single digit of the number of decades after 30. Then multiply this by an eighth (0.125) and finally add this number onto the height to get the number you need.

A useful function to round down integers:
num -= (num % 10);
You can make use of the fact that integer division automatically rounds down to the nearest integer:

1
2
3
4
5
6
7
8
9
10
11
12
13
14

void jacketSize(float height[], float weight[], float age[])
{
     float jacket[10];
     int i;

     for(int i = 0; i < 10; i++)
     {
          jacket[i] = (height[i] + ( 0.125*((int)(age[i])/10 - 3))*weight[i]/288;
     }
     
     return;
}


This code only works if age[i] >= 40 for all i. You'd have to tailor the problem if age[i] < 40 is allowed.
Last edited on
Lines 7,11,13,16 really don't accomplish anything. They set jacket[i], but jacket is a local array that goes out of scope when your function exits. You lose your calculations stored in jacket.
Last edited on
Topic archived. No new replies allowed.