c++ - i have multiple float variables that represent the probability of a specif
ID: 3817847 • Letter: C
Question
c++ - i have multiple float variables that represent the probability of a specific outcome occuring. These are all initialized as 0.33 initialy, but i have a function that passes 3 of the 9 variables at a time by reference and within the function the values of those 3 variables get adjusted. (even though its 3 at a time usually all 9 will eventual pass through the function). The function is called through a for loop, therefore each iteration adjusts 3 of the 9 variable values. The issue is that i need to have access to the largest value of those 9 floats after each iteration but i cannot find a way to do so. I tried using an array, but if the array is declared outside of main() it remains fixed at 0.33 for all variables, if i declare the array right after the for loop it only get the last adjusted values, and within the loop array values only change once. The primary purpose is to know which of the 9 floats has the highest value after each iteration, therefore if there is a more efficent way to find that instead of getting the largest value of the 9 and then using if statement to identify which one of the 9 is = to that largest value would be greatly apprienciated.
Explanation / Answer
You can do something like this
#include <stdio.h>
#include <stdlib.h>
double floatRand()
{
return (double)rand() / (double)RAND_MAX ;
}
void change(float *a, float *b, float *c)
{
*a = (*a + floatRand());
*b = (*b + floatRand());
*c = (*c + floatRand());
}
float largest(float a, float b, float c, float l)
{
float max = a;
if (b > max)
max = b;
if (c > max)
max = c;
if (l > max)
max = l;
return max;
}
int main()
{
float a,b,c,d,e,f,g,h,i;
a=b=c=d=e=f=g=h=i = 0.33;
printf("%f %f %f %f %f %f %f %f %f ", a,b,c,d,e,f,g,h,i);
int i;
float max = a;
for(i = 0; i < 3; i++)
{
change(&a, &b, &c);
max = largest(a, b, c, max);
}
return 0;
}
basically whatever three values you are passing to your function pass them to largest(val1, val2, val3, max) and max and store in max. Please note these are passed by value. This way you will maintain your largest value so far.
Hope this helped. Will look for a thumsup form you.
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.