正如标题所说,我需要对3个数字进行升序排序,而不使用无效交换等。我可以使用else,如果else.The 3数字不需要不同,例如,我们可以使用: a -5,b -5,c-10,输出应该是-5-5 10。我这样做是为了一个在线学习程序,但我的代码得到了100分中的93分,因此我不能跳到下一课。这是我的代码:
#include <iostream>
using namespace std;
int main() {
int a, b, c;
cin >> a >> b >> c;
if ( a < b && b < c ) {
cout << a << " " << b << " " << c;
} else if ( a > b && b > c ) {
cout << c << " " << b << " " << a;
}
if ( a < c && b < a ) {
cout << b << " " << a << " " << c;
}
if ( a < c && c < b ) {
cout << a << " " << c << " " << b;
} else if ( a > c && b > a ) {
cout << c << " " << a << " " << b;
}
if ( a == b && b == c ) {
cout << a << " " << b << " " << c;
} else if ( a == c && b == a ) {
cout << b << " " << c << " " << a;
}
if ( a == b && c < a ) {
cout << c << " " << b << " " << a;
} else if ( a == b && c > a ) {
cout << b << " " << a << " " << c;
}
if ( a == c && b < a ) {
cout << b << " " << c << " " << a;
} else if ( a == c && b > a ) {
cout << a << " " << c << " " << b;
}
if ( b == c && a < b ) {
cout << a << " " << b << " " << c;
} else if ( b == c && a > b ) {
cout << b << " " << c << " " << a;
}
return 0;
}提前谢谢你。
发布于 2020-10-05 19:28:57
使用min/max函数的值较小,但我觉得可能有更好的方法来找到的中间值。
int min = std::min(a, std::min(b, c));
int max = std::max(a, std::max(b, c));
std::cout << min << " ";
int middle = a; // By default a, in case none of the following conditions is true
if (a != min && a != max)
middle = a;
else if (b != min && b != max)
middle = b;
else if (c != min && c != max)
middle = c;
std::cout << middle << " " << max;发布于 2020-10-05 19:25:49
这样如何:
int x[3];
// first we compute the smallest
x[0] = min(a, min(b, c));
// then the biggest
x[2] = max(a, max(b, c));
// finally we take the remaining one as the middle element. For that we use this substraction trick
x[1] = a+b+c - x[0]-[2];
// NOTE: if you are worried about overflow, you can use the following XOR hack:
// x[1] = a^b^c ^ x[0]^x[2];
// unlike with +/-, this is well defined behaviour (note that this is a problem only for `int`, `unsigned` overflow is well defined, so it would work even it overflows)
cout << x[0] << " " << x[1] << " " << x[2] << endl;发布于 2020-10-05 19:40:32
这可以使用下面的if-else语句序列来完成。
if ( !( b < a ) && !( c < a ) )
{
if ( !( c < b ) )
{
std::cout << a << ' ' << b << ' ' << c << '\n';
}
else
{
std::cout << a << ' ' << c << ' ' << b << '\n';
}
}
else if ( !( a < b ) && !( c < b ) )
{
if ( !( c < a ) )
{
std::cout << b << ' ' << a << ' ' << c << '\n';
}
else
{
std::cout << b << ' ' << c << ' ' << a << '\n';
}
}
else if ( !( a < c ) && !( b < c ) )
{
if ( !( b < a ) )
{
std::cout << c << ' ' << a << ' ' << b << '\n';
}
else
{
std::cout << c << ' ' << b << ' ' << a << '\n';
}
}https://stackoverflow.com/questions/64207522
复制相似问题