Simple logic problem: Finding largest and smallest number among 3 numbers
I am creating a pseudocode in determining the smallest and largest number among 3 numbers:
My code is as follows:
If (x >= y)
largest = x
Smallest = y
Else
largest = y
Smallest =x
If (z >= largest)
La开发者_JAVA技巧rgest = z
If (z <= smallest)
Smallest = z
Do you think this is correct? or are there better ways to solve this?
Let's say you've got arbitrary numbers x, y, z
.
Pseudocode:
largest = x
smallest = x
if (y > largest) then largest = y
if (z > largest) then largest = z
if (y < smallest) then smallest = y
if (z < smallest) then smallest = z
This is one way to solve your problem if you're using only variables, assignment, if-else and comparison.
If you have arrays and a sort operation defined over it, you can use this:
array = [x, y, z]
arrays.sort()
largest = array[2]
smallest = array[0]
If you have a max
and min
function that takes an array of numbers as an argument, you can use this:
array = [x, y, z]
largest = max(array)
smallest = min(array)
If you also have positional assignment using sets, you can use this:
array = [x, y, z]
(largest, smallest) = (max(array), min(array))
If you have a data structure that will sort it's contents when inserting elements, you can use this:
array.insert([x, y, z])
smallest = array[0]
largest = array[2]
#include <stdio.h>
#include <algorithm>
using namespace std;
int main ( int argc, char **argv ) {
int a = 1;
int b = 2;
int c = 3;
printf ( "MAX = %d\n", max(a,max(b,c)));
printf ( "MIN = %d\n", min(a,min(b,c)));
return 0;
}
Something like this would be more general (in Java):
// All available values.
int[] values = new int[] { 1, 2, 3 };
// Initialise smallest and largest to the extremes
int smallest = Integer.MAX_VALUE;
int largest = Integer.MIN_VALUE;
// Compare every value with the previously discovered
// smallest and largest value
for (int value : values) {
// If the current value is smaller/larger than the previous
// smallest/largest value, update the reference
if (value < smallest) smallest = value;
if (value > largest) largest = value;
}
// Here smallest and largest will either hold the initial values
// or the smallest and largest value in the values array
if (x < y) {
minimum = min(x,z)
maximum = max(y,z)
} else {
minimum = min(y,z)
maximum = max(x,z)
}
Represent numbers with a, b, and c, assuming no two numbers are equal.
Read the three numbers
- If a is less than b, then if a is less than c print a, otherwise print c
- If b is less than a, then if b is less than c print b, otherwise print c
精彩评论