我目前正在尝试编写一个程序,该程序需要三个整数,并对它们进行排序(从最小到最大),然后将它们与键入的原始顺序一起输出。该程序有很多错误,例如,当我输入“ 4 7 9”时,程序会将其分类为“ 4 9 9”。但是,如果我执行“ 65 32 11”,则程序会将其正确排序为“ 11 32 65”。我只是想知道我的代码出了什么问题,以及如何改进它以及将来的项目。
cout << "Please input 3 integers with a space inbetween them.\n";
int v1;
int v2;
int v3;
int smallest = 0;
int middle = 0;
int largest = 0;
cin >> v1 >> v2 >> v3;
if (v1 <= v2 && v1 <= v3) {
smallest = v1;
if (v2 <= v3) {
middle = v2;
largest = v3;
}
else
largest = v2;
middle = v3;
}
else if (v2 <= v1 && v2 <= v3) {
smallest = v2;
if (v1 <= v3) {
middle = v1;
largest = v3;
}
else
largest = v1;
middle = v3;
}
else {
smallest = v3;
if (v1 <= v2) {
middle = v1;
largest = v2;
}
else
largest = v1;
middle = v2;
}
cout << "Input values: " << v1 << ", " << v2 << ", " << v3 << '\n';
cout << "Sorted values: " << smallest << ", " << middle << ", " << largest << '\n';
keep_window_open();
}
答案 0 :(得分:2)
cout << "Please input 3 integers with a space inbetween them.\n";
int v1;
int v2;
int v3;
int smallest = 0;
int middle = 0;
int largest = 0;
cin >> v1 >> v2 >> v3;
if (v1 <= v2 && v1 <= v3) {
smallest = v1;
if (v2 <= v3) {
middle = v2;
largest = v3;
}
其他部分缺少{}
else{
largest = v2;
middle = v3;
}
}
else if (v2 <= v1 && v2 <= v3) {
smallest = v2;
if (v1 <= v3) {
middle = v1;
largest = v3;
}
其他部分缺少{}
else{
largest = v1;
middle = v3;
}
}
else {
smallest = v3;
if (v1 <= v2) {
middle = v1;
largest = v2;
}
其他部分缺少{}
else{
largest = v1;
middle = v2;
}
}
cout << "Input values: " << v1 << ", " << v2 << ", " << v3 << '\n';
cout << "Sorted values: " << smallest << ", " << middle << ", " << largest << '\n';
keep_window_open();
}
如果您查看所有if else的else部分,就会发现{}
丢失了您的最大和中间价值。
更多信息...
if(condition) /* if statement with condition */
statement; /* executes if the if condition is true even without the {} */
else /* else statement when if condition is false */
statement; /* executes when else is true without the {} */
statement; /* Visually misguided but execution does not depend
upon the else statement, this line always gets executed,
compiler only looks at the first line after if else without {} */
答案 1 :(得分:2)
首先出现在我身上的是您的else语句。在C / C ++中,不带括号的else
语句将在条件满足时执行下一条语句。如果不存在大括号,它将不会执行多个语句。这在代码中是有问题的,因为无论您的第二级middle
语句如何,您的if
值都会被覆盖。作为参考,可以在SO的软件工程页面上查看discussion。
替换
if (v1 <= v2 && v1 <= v3) {
smallest = v1;
if (v2 <= v3) {
middle = v2;
largest = v3;
}
else
largest = v2;
middle = v3;
}
使用
if (v1 <= v2 && v1 <= v3) {
smallest = v1;
if (v2 <= v3) {
middle = v2;
largest = v3;
}
else
{
largest = v2;
middle = v3;
}
作为旁注,如果您要考虑更多位数,则应考虑实现Radix排序。单击此处获取Radix Sorting Algorithm Tutorial