how do I optimize this code? I actually want to create a function like swap_and_return which should return from the function if done. but I could not do it.
we can see that I wrote a lot of print values and swap values which I could've written maybe inside of swap function.
what are your suggestions?
void swap(int *i, int *j) {
int t = *i;
*i = *j;
*j = t;
}
void print_values(int x, int y, int z) {
cout << "x=" << x << ", y=" << y << ", z=" << z << "
";
}
float min_max(int x, int y, int z) {
float avg = 0;
if(x<y && x<z){
if (y < z) {
swap(&x, &z);
print_values(x, y, z);
avg = (x + z) / 2.0;
return avg;
}
else {
swap(&x, &y);
print_values(x, y, z);
avg = (x + y) / 2.0;
return avg;
}
}
else if(y<x && y<z){
if (x < z) {
swap(&y, &z);
print_values(x, y, z);
avg = (y + z) / 2.0;
return avg;
}
else {
swap(&y, &x);
print_values(x, y, z);
avg = (y + x) / 2.0;
return avg;
}
}
else if(z<y && z<x){
if (x < y) {
swap(&z, &y);
print_values(x, y, z);
avg = (z + y) / 2.0;
return avg;
}
else {
swap(&z, &x);
print_values(x, y, z);
avg = (z + x) / 2.0;
return avg;
}
}
return avg;
}
int main()
{
float value = min_max(5, 1, 2);
cout << value << "
";
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…