仅使用 if else 语句对数字进行排序时遇到问题
Having trouble sorting numbers with only if else statments
对于这项作业,我的教授要求我创建一个程序,要求用户输入 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";
相关文章:
- 使用自定义比较函数使用std::sort()对矢量字符串进行排序时出现问题
- 排序算法问题(购买商店物品)(崩溃)
- 在C++中对结构向量进行排序时出现问题
- 数组为此合并排序函数提供了正确的输出,但向量给出了不正确的输出.出了什么问题?
- 如何解决索引和排序问题
- 从priority_queue弹出时出现排序问题,这是 std::p riority_queue 的错误吗?
- 给定数组范围的选择排序问题
- C++合并排序问题
- 在 c++ 中将数字从列表排序到数组中的气泡排序问题
- 气泡排序问题C++
- 气泡排序问题不会更改输入阵列
- 具有双重类型的C++快速排序问题
- 插入排序问题
- 合并排序问题,在方法之间传递数组
- C++ 将多索引提升为 LRU 缓存的索引排序问题
- 快速排序问题c++
- 选择排序C++问题
- 气泡排序问题
- Android Studio中的Gradle任务排序问题
- 按引用传递 - C++:合并排序 问题:超出范围