| jblv (5) | |
|
Hello everyone! I have randomly generated array of floats and I need to multiply the values between min and max value of the array, for example, if the array is: 1 3 4 8 5 then product should be 12 (3 * 4) since these values are between 1 and 8. float max = arr[0]; float min = arr[0]; for (int i = 0; i < n; i++) { if (arr[i] > max) max = arr[i]; if (arr[i] < min) min = arr[i]; } cout << max << endl << min << endl; float product = 1; for (int i = min; i < max; i++) { if (arr[i] > min && arr[i] < max) { product = product * arr[i]; } } When writen like this, it is multiplying all the value that are bigger than min and smaller than max, but I need to multiply only those between min and max. I am bit stuck, could anyone help out? Many thanks in advance. | |
|
|
|
| EssGeEich (1007) | |||||
You meant this I hope:
| |||||
|
|
|||||
| Athar (4466) | |
| It's not sufficient to keep track of the min and max values, you also need to keep track of their index. | |
|
|
|
| vlad from moscow (3662) | |||
| |||
|
Last edited on
|
|||
| jblv (5) | |
|
Thank's everyone. Vlad, thank you, but I am at the very beggining of C++ and could not understand what needs to be done from your code. Well, I tried to keep track on their indexes, but still nothing.. maybe additional help could be provided. This is how far I have got. float max = arr[0]; float min = arr[0]; int minIndex = 0, maxIndex = 0; float temp, temp2; for (int i = 0; i < n; i++) { if (arr[i] < min) { min = arr[i]; minIndex = i; } if (arr[i] > max) { max = arr[i]; maxIndex = i; } if(max < min) { temp = max; max = min; min = temp; } } cout << minIndex << endl << maxIndex << endl; float product = 1.00; for (int i = minIndex + 1; i < maxIndex; i++) { product = product * arr[i]; } cout << "Product of values between maximum and minimum values: " << product << endl; | |
|
Last edited on
|
|
| Zhuge (2974) | |
|
Could you use [code][/code] tags? And what output are you getting? (compared to what you are expecting.) | |
|
|
|
| vlad from moscow (3662) | |||
|
You should write two functions. The first one will find the index of the minimal element of the array and the second one will find the maximum element of the array. For example
The same way you should write function max_element. Then you should determine whether the minimum or maximum element has the smalest index and calculate the product. | |||
|
Last edited on
|
|||
| jblv (5) | |||
Thanks for help everyone! Came out with this such resolution:
| |||
|
Last edited on
|
|||