Finding Mid Value

My is assignemnt is as follows...
The program has an expression statement to initialize x, y and z. It has another statement to make the variable the actual mid value of the three variables, x, y and z.

Change the right-hand side of the statement that changes mid so that it correctly figures out the mid value of the three variables. Note that your code must work regardless of how x, y and z are initialized, and not just for the test case as provided in the code itself.

I can use as many operators as i want but i cannot use any conditional statements like if, or any loops. only operators. Here is the code
1
2
3
4
5
6
7
8
9
10
  int main
{
 int, x, y, z;
 int mid;

x=2, y=6, z=3;
TestLabel:
 mid= (0); // replace the RHS of this assignment so mid is the middle value of x, y and z
 return 0;
}
So, why don't use simple mathematics. You also have to notice, that, if you have uneven numbers, you will not get an integer value, or the compiler/program will round off the value (i.e. 4.7 -> 5).

But the mathematical way to calculate a "mid" is to add all numbers to one another and then divide them by their "number"

1
2
2 + 6 + 3 = 11
-> 11/3 //Because we have three different numbers/values 


This is just pseudo code to be honest. But a simple integration would look this way:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
#include <iostream>


int main() {

	float  x,
		y,
		z;
	float mid;

	x = 2.0f;
	y = 6.0f;
	z = 3.0f;

	mid = (x + y + z) / 3;
	std::cout << mid << std::endl;

return 0;
}


You can replace the simple calculation by adding a (stupid, but easier to understand) solution, on why the dividend is 3:

1
2
3
4
5
6
x = 2;
	y = 6;
	z = 3;

	mid = (x + y + z) / (x/x + y/y + z/z); // Because the quotient of x/x (i.e) is always 1 (except for x = 0)
	std::cout << mid << std::endl;
Last edited on
Topic archived. No new replies allowed.