【问题标题】:Vscode Complies the sorting algorithms but does not give any output. These are running fine in an online compiler.[I have MinGW installed]Vscode 遵循排序算法但不给出任何输出。这些在在线编译器中运行良好。[我安装了 MinGW]
【发布时间】:2021-01-02 04:47:04
【问题描述】:
/*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;
}

附加的图像显示了我在运行相应代码时在终端中获得的输出(空白)。第一个算法说明了冒泡排序算法,第二个算法旨在实现插入排序技术。 非常感谢这方面的任何帮助!

在终端中输出冒泡排序代码

在终端中输出插入排序代码

【问题讨论】:

  • 您的程序有未定义的行为,可能会或可能不会工作。当您编写 int r[l]; 时,当您稍后决定 l 是什么时,向导不会神奇地调整数组的大小。
  • 你的程序永远不会做你想做的事,而是你告诉它做的事;)像r[l]这样的VLA也是not part of the C++ standard,请改用std::vector

标签: c++ visual-studio-code mingw


【解决方案1】:

main 的这一部分包含典型的 C++ 新手错误。

int l; 
int r[l];
cout<<"Enter the array size"<<endl;
cin>>l;

当你写int l时,你只保留一些内存并给它起一个好听的名字ll 的值是任意的,或者是垃圾。然后你写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),他们会发出大量诊断信息。处理您的源代码,直到您看不到任何错误和警告为止。

【讨论】:

    猜你喜欢
    • 2022-11-27
    • 2016-01-02
    • 2014-11-08
    • 2017-05-28
    • 1970-01-01
    • 1970-01-01
    • 2012-09-21
    • 2021-12-31
    • 2021-06-15
    相关资源
    最近更新 更多