don't get the desired output

: 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)

temp=x;
x=y;
y=temp;

ans=x;
x=z;
z=ans;

}


1. You have to use reference parameters. Your current function takes parameters by value and therefore will not adjust the variables of the caller.

2. Only the "temp=x; is affected by the if-clause.

3. Your single if-clause cannot cover 6 possible combinations.
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
What parts do you not understand?

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].
Can someone correct my code.I did a lot of changes in the code even though don't get the desired output.
closed account (zybCM4Gy)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <iostream>

using namespace 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.
Topic archived. No new replies allowed.