Simple program but wrong output
2 Ansichten (letzte 30 Tage)
Ältere Kommentare anzeigen
Dave Mosooka
am 15 Dez. 2016
Beantwortet: Walter Roberson
am 15 Dez. 2016
My program gets three unique points (positive integers) and should rearrange them so they are in order from point 1 to 3 but when I print the variables at the end they are sometimes not in order. My code is pretty straight forward and I think it's obvious what I am trying to do but I must be doing something wrong here?
%get unique points
point1 = randomPoint();
point2 = point1;
point3 = point1;
while point1 == point2
point2 = randomPoint();
end
while point1 == point3 || point2 == point3
point3 = randomPoint();
end
%check ordering
if point1 > point2
temp = point1;
point1 = point2;
point2 = temp;
end
if point2 > point3
temp = point2;
point2 = point3;
point3 = temp;
end
display(point1);
display(point2);
display(point3);
-
function [point] = randomPoint()
%get random points
point = 0; %1, 4, 7, 10, 13, 16, 19, 22, 25, 28
while mod(point, 3) ~= 1 %fall on start of fsm state
point = randi([1,28]);
end
end
Example output: >> run main
point1 =
13
point2 =
10
point3 =
19
0 Kommentare
Akzeptierte Antwort
Walter Roberson
am 15 Dez. 2016
After you swap point 3 down to point 2, you need to figure out whether it then needs to be swapped down to point 1. Consider for example, [6 5 4] then your first operation would swap to [5 6 4] and your second operation would swap that to [5 4 6] but you need to compare that 5 and 4.
0 Kommentare
Weitere Antworten (1)
David Barry
am 15 Dez. 2016
Instead of:
%check ordering
if point1 > point2
temp = point1;
point1 = point2;
point2 = temp;
end
if point2 > point3
temp = point2;
point2 = point3;
point3 = temp;
end
Try something like:
sortedPoints = sort([point1, point2, point3]);
point1 = sortedPoints(1);
point2 = sortedPoints(2);
point3 = sortedPoints(3);
0 Kommentare
Siehe auch
Kategorien
Mehr zu Annotations finden Sie in Help Center und File Exchange
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!