c++ - Vscode 遵循排序算法但不给出任何输出。这些在在线编译器中运行良好。[我安装了 MinGW]
问题描述
/*Bubble sort*/
#include <iostream>
using namespace std;
//function to sort the array
int bubble_sort (int k[], int n){
int t,ct=1;
while(ct<n){
for(int i=0;i<n-ct;i++){
if(k[i]>=k[i+1]){
t=k[i];
k[i]=k[i+1];
k[i+1]=t;
}
ct++;
}
}
///loop to o/p the sorted array
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
bubble_sort(r,l);
return 0;
}
/*Insertion Sort*/
#include <iostream>
using namespace std;
//function to sort the array
int insertion_sort (int k[], int n){
int t,ct=1;
for(int i=1;i<n;i++){
int current=k[i];
int j=i-1;
while(k[j]>current && j>=0){
k[j+1]=k[j];
j--;
}
k[j+1]=current;
}
for(int i=0;i<n;i++){
cout<<k[i]<<" ";
}cout<<endl;
return 0;
}
int main(){
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
cout<<"Enter elements"<<endl;
for(int i=0;i<l;i++){
cin>>r[i];
}
insertion_sort(r,l);
return 0;
}
所附图像显示了我在运行相应代码时在终端中获得的输出(空白)。第一个算法说明了冒泡排序算法,第二个算法旨在实现插入排序技术。非常感谢这方面的任何帮助!
在终端中输出冒泡排序代码
在终端中输出插入排序代码
解决方案
这部分main
包含典型的 C++ 新手错误。
int l;
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;
当你写的时候int l
,你只保留一些内存并给l
它起一个好听的名字。的值l
是任意的,或者是垃圾。然后你写int r[l]
。这有几个问题。首先,C++ 语言不允许这样的数组定义,除非l
是编译器知道其值的常量。所以这是一个错误,但许多编译器不会将其标记为错误,因为它们神奇地允许这种特定的偏离标准并将其称为“扩展”(VLA)。它的代价是你的程序不是标准的,它的行为可能依赖于编译器。其次,如您所知, 的值l
是未定义的。因此,您的程序的任何执行都可能导致不同的输出,包括正确的(预期的)行为甚至突然死亡(崩溃)。
你需要做的是:
- 声明一个将存储数组大小的变量。给它一个有意义的名字,比如
size
,避免使用类似的名字l
,因为它们有时很难从 1 和 I 中分辨出来。 - 从
std::cin
- 构造一个大小为 的数组
size
。不要使用int a[size]
语法,因为您已经知道标准不允许这样做。使用 std::vector。
如果在这些更改之后您的程序仍然以奇怪的方式运行,请再次寻求帮助。
此外,在您再次寻求帮助之前,请在以下位置添加这些标志gcc
:
-Wall -pedantic
如果您的程序不遵守通常的编码标准 ( -Wall
) 或 C++ 标准 ( -pedantic
),他们将发布大量诊断信息。处理您的源代码,直到您看不到任何错误和警告。
推荐阅读
- wso2 - 如何自定义 wso2 api manager 错误格式?
- java - 可以使用从远程主机连接的 java 代理来传递数据吗?
- amazon-web-services - 在 AWS Elastic Beanstalk 中部署烧瓶应用程序时出现 require.txt 的问题
- sql - SQLite:按 NULL 值的数量排序
- android - 使用工具栏中的按钮在片段之间导航
- html - 是什么让两个具有相同 CSS 属性的元素看起来不同?
- sql - SQL Server:合并迭代
- sql - 在 Athena 或 Quicksight 上滚动计数
- python - QueryDict 对象没有属性会话 Django
- python - 如何使用 selenium python 延迟单击并按住