C Exercise Example 5
Title:Input three integers x, y, z, and output these three numbers in order from smallest to largest.
Program analysis:We find a way to put the smallest number on x: first compare x with y; if x>y, swap the values of x and y. Then compare x with z; if x>z, swap the values of x and z. This way, x becomes the smallest.
Example 1
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example. All rights reserved.
//
#include <stdio.h>
int main()
{
int x,y,z,t;
printf("\nPlease enter three numbers:\n");
scanf("%d%d%d",&x,&y,&z);
if ( x>y ) {
/*Swap the values of x and y*/
t=x; x=y; y=t;
}
if ( x>z ) {
/*Swap the values of x and z*/
t=z; z=x; x=t;
}
if ( y>z ) {
/*Swap the values of z and y*/
t=y; y=z; z=t;
}
printf("Sort from small to large: %d %d %d\n",x,y,z);
}
The output result of the above example is:
请输入三个数字: 1 3 2 从小到大排序: 1 2 3
Example 2
// Created by www.example.com on 15/11/9.
// Copyright © 2015 Example Tutorial. All rights reserved.
//
#include <stdio.h>
// Swap the values of two variables
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b, c;
printf("\nPlease enter three numbers:\n");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
swap(&a, &b);
}
if (a > c) {
swap(&a, &c);
}
if (b > c) {
swap(&b, &c);
}
printf(\"Sort from small to large: %d %d %d\n", a, b, c);
return 0;
}
// Copyright © 2015 Example Tutorial. All rights reserved.
//
#include <stdio.h>
// Swap the values of two variables
void swap(int *a, int *b) {
int temp = *a;
*a = *b;
*b = temp;
}
int main() {
int a, b, c;
printf("\nPlease enter three numbers:\n");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
swap(&a, &b);
}
if (a > c) {
swap(&a, &c);
}
if (b > c) {
swap(&b, &c);
}
printf(\"Sort from small to large: %d %d %d\n", a, b, c);
return 0;
}