如何解决在我的 C++ 冒泡排序代码中,当我按升序输入时,我的输出有问题
当我以降序输入(如 4321
)时,它工作正常,但当我更改顺序时,即使更改了一个位置(如 1432
for(int pass = 1; pass <= n-1; pass++)
{
for(int j = 0; j < n-pass; j++)
{
if( a[j] > a[j+1])
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
}
输出
Enter the size of the array
4
Enter the elements of the array
1
4
3
2
Elements of the array are :
1432
Elements of the sorted array are :
0001
解决方法
您缺少括号。
默认情况下,if 的下一行被认为在范围内
如果你在 if 之后不加括号。
它导致了一些严重的错误 Apple Bug
for(int pass = 1; pass <= n-1; pass++)
{
for(int j = 0; j < n-pass; j++)
{
if( a[j] > a[j+1]) { // here
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp; } //here
}
}
,
为 if 条件添加一个括号,例如:
if( a[j] > a[j+1]){
temp = a[j+1];
a[j+1] = a[j];
a[j] = temp;
}
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。