请用c++语言,编写一个- 输入a, b, c三个整数,按照由小到大的顺序输出。 编程思路: (1)输入三个整数a, b, c; (2)然后用传参方式调用swap函数来实现3个整数变量的互换; (3)输出最大数a和最小数b
时间: 2024-05-22 19:14:15 浏览: 9
,中间数c即可。 代码如下:
#include <stdio.h>
void swap(int* x, int* y) {
int temp = *x;
*x = *y;
*y = temp;
}
int main() {
int a, b, c;
printf("请输入三个整数a, b, c:\n");
scanf("%d %d %d", &a, &b, &c);
if (a > b) {
swap(&a, &b); // 交换a和b
}
if (a > c) {
swap(&a, &c); // 交换a和c
}
if (b > c) {
swap(&b, &c); // 交换b和c
}
printf("%d %d %d", b, c, a); // 输出结果,按由小到大的顺序
return 0;
}
相关问题
c++编写:输入3个整数a、b、c,按从大到小的顺序输出。要求通过指针实现
这是一个比较简单的编程问题,可以通过以下代码实现:
```c
#include <stdio.h>
void sort_desc(int *a, int *b, int *c);
int main() {
int a, b, c;
printf("请输入3个整数:");
scanf("%d %d %d", &a, &b, &c);
sort_desc(&a, &b, &c);
printf("按照从大到小的顺序输出:%d %d %d", a, b, c);
return 0;
}
void sort_desc(int *a, int *b, int *c) {
int temp;
if (*a < *b) {
temp = *a;
*a = *b;
*b = temp;
}
if (*a < *c) {
temp = *a;
*a = *c;
*c = temp;
}
if (*b < *c) {
temp = *b;
*b = *c;
*c = temp;
}
}
```
上面的代码是通过指针实现从大到小排序的,可以输入任意三个整数,并将它们按照从大到小的顺序进行输出。
读入三个不同的整数,编程按由小到大的顺序排列出来,中间用一空格隔开。 Input 输入三个不同的整数 Output 按由小到大输出三个整数,中间用一空格隔开 Sample Input 3 5 2 Sample Output 2 3 5c++代码
下面是一个用C++编写的解决方案:
```cpp
#include <iostream>
#include <algorithm>
int main() {
int a, b, c;
std::cin >> a >> b >> c;
int arr[] = {a, b, c};
std::sort(arr, arr + 3);
std::cout << arr[0] << " " << arr[1] << " " << arr[2] << std::endl;
return 0;
}
```
在这个例子中,我们首先声明三个变量`a`,`b`和`c`来存储输入的三个整数。然后,我们使用`std::cin`从标准输入流中读取这三个整数。
接下来,我们将这三个整数放入数组`arr`中,并使用`std::sort`对数组进行排序,以从小到大的顺序排列。
最后,我们使用`std::cout`将排序后的三个整数按照要求输出到标准输出流中,并在每两个整数之间添加一个空格。
通过运行这段代码,并给定示例输入`3 5 2`,将会得到输出:
```
2 3 5
```
希望这可以帮助到您!如果您有任何其他问题,请随时提问。