仅使用 if else 语句对数字进行排序时遇到问题

Having trouble sorting numbers with only if else statments

本文关键字:排序 问题 遇到 数字 if else 语句      更新时间:2023-10-16

对于这项作业,我的教授要求我创建一个程序,要求用户输入 3 个整数并按从大到小的顺序将它们打印出来。例如:输入为10、4、6,输出应为10、6、4我只允许使用 if else 语句,这就是我到目前为止所拥有的,但是当我编译时,它说我的变量position_1 - position_3没有初始化,我的输出也遇到了问题。

#include <iostream>
using namespace std;
int main()
{
int x;
int y;
int z;
int position_1;
int position_2;
int position_3;
cout<<"Please enter your first integer value"<<endl;
cin>>x;
cout<<"Please enter your second integer value"<<endl;
cin>>y;
cout<<"Finally enter your third integer value"<<endl;
cin>>z;
if(x>y && x>z)
x=position_1;
else if (x  >y && x < z)
x=position_2;
else if (x <y && x > z)
x=position_2;
else 
x=position_3;
if(y>x && y>z)
y=position_1;
else if (y >x && y < z)
y=position_2;
else if (y <x && y > z)
y=position_2;
else 
y=position_3;
if(z>x && z>y)
z=position_1;
else if (z >x && z < y)
z=position_2;
else if (z <x && z > y)
z=position_2;
else 
z=position_3;
cout<<position_1 + " " + position_2 + " " + position_3.n;
system("pause");
return 0;
}

你似乎反过来写作业。 你可能想说

position_1 = x;

而不是

x=position_1;

等等...

这更有可能起作用...我没有尝试过,因为我在编译器方面有一些问题,但我认为它应该可以工作。

#include <iostream>
using namespace std;
int main()
{
int x, y, z;
int position_1, position_2, position_3;
cout<<"Please enter your first integer value"<<endl;
cin>>x;
cout<<"Please enter your second integer value"<<endl;
cin>>y;
cout<<"Finally enter your third integer value"<<endl;
cin>>z;
if(x>y&&x>z){
    position_1 = x;
    if(y>z){
        position_2 = y;
        position_3 = z;
    }
    else{
        position_2 = z;
        position_3 = y;
    }
}
else if(y>x&&y>z){
    position_1 = y;
    if(x>z){
        position_2 = x;
        position_3 = z;
    }
    else{
        position_2 = z;
        position_3 = x;
    }
}
else if(z>x&&z>y){
    position_1 = z;
    if(y>x){
        position_2 = y;
        position_3 = x;
    }
    else{
        position_2 = x;
        position_3 = y;
    }
}
cout << position_1 << " " << position_2 << " " << position_3;
cin.get();
cin.get();
}

我已经快一年没有用 c++ 编程了,但我认为这在 c++ 中不起作用

cout<<position_1 + " " + position_2 + " " + position_3.n;

据我所知,它应该是这样的:

cout<<position_1 << " " << position_2 << " " << position_3 <<"n";

这应该可以做到:

if(x>=y && x>=z)
{
  position_1 = x;
  if(y>=z)
  {
    position_2 = y;
    position_3 = z;
  }
  else
  {
    position_3 = y;
    position_2 = z;
  }
}
else
{
  if (x>=y || x>=z)
  {
    position_2 = x;
    if(y>=z)
    {
      position_1 = y;
      position_3 = z;
    }
    else
    {
      position_3 = y;
      position_1 = z;
    }
  }
  else
  { 
    position_3 = x;
    if(y>=z)
    {
      position_1 = y;
      position_2 = z;
    }
    else
    {
      position_2 = y;
      position_1 = z;
    }
  }
}
cout<<position_1<<" "<<position_2<<" "<<position_3<<"n";