: Write a function named "sort3" that takes three floating point arguments, call them "x", "y" , and "z", and modifies their values, if necessary, in such a way as to make true the following inequalities: x (LE) y (LE) z . The function should return no value. To take an example, if the following code fragment is executed
float a = 3.2, b = 5.8, c = 0.9;
sort3 (a, b, c);
cout<< a << " " << b << " " << c <<endl;
then the output will be
0.9 3.2 5.8
#include<iostream>
using namespace std;
void sort3(float a,float b,float c);
int main()
{
float a = 3.2, b = 5.8, c = 0.9;
sort3 (a, b, c);
cout<< a << " " << b << " " << c <<endl;
system("pause");
}
void sort3(float x,float y,float z)
{
float temp=0,ans=0;
if (x<y && x>z)
I don't get it. Could you explain me what are you trying to say. I used cout expression in that sort 3 function and it gives me the desired output , but the above code gives the output 3.2 5.8 0.9
He mentioned the functions 1) do not modify the values outside of the function scope. 2) your if statement only assigns the value of x to temp. 3) you only go through 1 scenario [zxy].
#include <iostream>
usingnamespace std;
void sort3(float a,float b,float c); //Why is this prototyped? Just have the function at the top.
int main()
{
float a = 3.2, b = 5.8, c = 0.9;
sort3 (a, b, c);
cout<< a << " " << b << " " << c <<endl;
}
void sort3(float x,float y,float z)
{
float temp=0,ans=0;
if (x<y && x>z) // This isn't doing anything. There are no braces.
temp=x;
x=y;
y=temp;
ans=x;
x=z;
z=ans;
}
Instead of passing by value, you'll want to pass by reference instead.
So instead of float x, y, z... you'll want float &x, &y, &z.
Passing by value copies the data into a new memory space (bad) and then you have to make sure it returns the answer...which is not what you're after.
Instead you want the function to manipulate the variables at their original address. This is where passing by reference comes in. So instead of creating a new physical copy of the value, you instead use the value you already have by using its memory address as a parameter.
&jack
Can be read as "At the physical address of"
So instead of altering a new copy, you're just working with the original value.