有没有更好的方法对C++中的三个整数进行排序?
Is there any better way to sort three integers in C++?
在我正在使用的编程教科书(Bjarne Stroustrup的编程:使用C++的原则和实践(中,我正在尝试做一个在早期章节中找到的练习(在引入数组或其他任何东西之前(,但我只能使用一种对我来说看起来很奇怪和"倒退"的算法来解决它。练习是从控制台读取 3 个整数,并根据大小对它们进行排序,用逗号分隔。这是我写的:
#include <iostream>
using namespace std;
int main()
{
int a, b, c;
cout << "Enter three integers: ";
cin >> a >> b >> c;
if (a <= b and a <= c) {
cout << a << ", ";
if (b < c)
cout << b << ", " << c;
else
cout << c << ", " << b;
return 0;
}
if (b <= a and b <= c) {
cout << b << ", ";
if (a < c)
cout << a << ", " << c;
else
cout << c << ", " << a;
return 0;
}
if (c <= a and c <= b) {
cout << c << ", ";
if (a < b)
cout << a << ", " << b;
else
cout << b << ", " << a;
return 0;
}
return 0;
}
我知道它很长,但我想不出任何其他方法可以使用我可以使用的工具(if 语句(来做到这一点。你能帮我看看是否有其他方法可以做到吗?谢谢!
取决于你所说的"更好"是什么意思。有一种更短的方法可以做到这一点,就像C++中的大多数其他事情一样:
#include <iostream>
#include <iterator>
#include <algorithm>
#include <cstdio>
int main() {
std::istream_iterator<int> it{std::cin};
int a[]{ *it++, *it++, *it++ };
std::sort(std::begin(a), std::end(a));
std::printf("%d, %d, %dn", a[0], a[1], a[2]);
}
是否越短越好是另一个讨论。
您也可以在不调用std::sort
的情况下执行此操作,手动排序:
// Put the smallest number in a.
if (b < a)
std::swap(a, b);
if (c < a)
std::swap(a, c);
// Arrange the other two numbers.
if (c < b)
std::swap(b, c);
std::cout << a << ", " << b << ", " << c << 'n';
希望这有帮助:
#include <iostream>
using namespace std;
int main()
{
int a, b, c, x, mid, max;
cout << "Enter three integers: ";
cin >> a >> b >> c;
if (a<b){
x = a;
max = b;
}
else {
x = b;
max = a;
}
if (c < x){
mid = x;
x = c;
}
if (c > max){
mid = max;
max = c;
}
else
mid = c;
cout << x << ", " << mid <<", "<<max;
}
相关文章:
- 模板-模板参数推导:三个不同的编译器三种不同的行为
- 在 2D 向量中使用第三个 [ ] 有什么意义?
- 如何通过按下第三个窗口中的按钮,将QString从一个窗口获取到另一个窗口
- 如何知道n!是否可以表示为三个连续数字的乘法?
- 我有三个 getline,但是一旦编译,输入就太多了
- 我遇到了黑客排名中的问题"TWO STRINGS"的三个测试用例的分段错误。原因是什么?
- 有没有更好的方法对C++中的三个整数进行排序?
- 如何检查第三个 API 是否在 Linux 中为 c/c++ 程序创建了一个新线程?
- 为什么 getch 在按下函数或箭头键时返回三个值?
- 使用三个数字比较器进行排序
- 升序,三个整数表示C++
- 在由空间隔开的线中输入三个整数
- 三个整数组成一个带空格的字符串;
- 确定 C++ 中整数集合中的第三个四分位数
- 如何设置整数的前三个字节?在C++中
- 三个有符号整数的哈希函数
- 如何将三个整数组合成一个唯一的标记,使标记在c++中保持整数
- 有三个不同整数的排序数组,只经过一次传递
- 如何通过cstdio::scanf在一行中读入三个整数
- 如何从三个整数生成constexpr版本的字符串(或者可能是git/SVNcommit/rev.string)