怎么编程排序三个整数

时间:2025-01-27 08:42:57 网络游戏

方法一:使用C++标准库中的`sort`函数

```cpp

include

include

include

int main() {

int a, b, c;

std::cin >> a >> b >> c;

std::vector numbers = {a, b, c};

std::sort(numbers.begin(), numbers.end());

for (size_t i = 0; i < numbers.size(); ++i) {

std::cout << numbers[i];

if (i < numbers.size() - 1) {

std::cout << " ";

}

}

std::cout << std::endl;

return 0;

}

```

方法二:使用if-else语句进行比较

```cpp

include

int main() {

int a, b, c, t;

printf("Please input a, b, c:\n");

scanf("%d, %d, %d", &a, &b, &c);

if (a > b) {

t = a;

a = b;

b = t;

}

if (a > c) {

t = a;

a = c;

c = t;

}

if (b > c) {

t = b;

b = c;

c = t;

}

printf("%d %d %d\n", a, b, c);

return 0;

}

```

方法三:使用指针方法

```cpp

include

void swap(int *a, int *b) {

int temp = *a;

*a = *b;

*b = temp;

}

int main() {

int a, b, c;

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("%d %d %d\n", a, b, c);

return 0;

}

```

方法四:使用函数模板进行排序

```cpp

include

include

template

void sort_three(T a, T b, T c) {

if (a > b) swap(a, b);

if (a > c) swap(a, c);

if (b > c) swap(b, c);

}

int main() {

int a, b, c;

std::cin >> a >> b >> c;

sort_three(a, b, c);

std::cout<< a << " "<< b << " "<< c << std::endl;

return 0;

}

```

这些方法都可以实现对三个整数的排序,你可以根据自己的需求和编程习惯选择合适的方法。