【问题标题】:sorting numbers and print stars in c++在 C++ 中排序数字并打印星星
【发布时间】:2021-12-29 06:05:07
【问题描述】:

我需要一个程序,它可以输入数字并打印与数字一样多的星星,然后对数字进行排序。 所有函数都必须在头文件中。

#include <iostream>
using namespace std;

 int read(int a[],int n)
 {
     int i=0;
     cout<<"please enter numbers: ";
     do
        cin>>a[i];
     while (a[i++]>-1 && i<n);
     return (i-1);
 }
 void print(int const a[], int const n)
 {
     for(int i=0;i<n;i++)
     cout<<a[i]<<"* ";
     cout<<endl;
 }
 void sort(int a[], int const n)
 {
     for (int i=1; i<n;i++)
        for(int j=0;j<n-i;j++)
        if(a[j]>a[j+1]) swap (a[j],a[j+1]);
 }

据我所知,但我不知道如何打印星星并在主程序中使用标题。

【问题讨论】:

  • 我怀疑没有方法被调用。我记得,c++在程序运行时调用main方法,w3schools.com/cpp/cpp_getstarted.asp
  • 函数为什么要放在头文件中?除非您创建函数inline,否则函数体属于实现文件,而不是头文件。对我来说,您需要做的就是在您发布的代码的底部添加main,而忘记头文件(除了&lt;iostream&gt;&lt;algorithm&gt;等必需的文件)

标签: c++


【解决方案1】:

以下是如何将程序添加到主程序。将您的程序保存为带有.h 扩展名的头文件。并在你的程序中包含#include yourfilename.h 在这里我假设你的文件名是program

    #include "program.h" // Here you are adding your program as a hadder.save your program with as program.h file
    #include <iostream>
    using namespace std;
    int main(){
      int a[100]; // define a array you can change the length of array also
      read(a,10); // calling the read function of your program a is the array a[] and 10 is the length of array or n
      sort(a,10);//calling the sort function of your program a is the array a[] and 10 is the length of array or n
      print(a,10);//calling the print function of your program a is the array a[] and 10 is the length of array or n
    }

【讨论】:

  • 感谢您的帮助。但是如果我不想设置数组的长度,它会将长度作为输入并做剩下的事情。
  • @mohamadrezajafarzadeh:#include &lt;vector&gt; ... int length; ... std::vector&lt;int&gt; a(length);。数组无法调整大小,这就是向量存在的原因。
  • 是的,这就是我使用 const number 的原因。有没有其他方法可以在没有向量的情况下做到这一点?
  • @mohamadrezajafarzadeh -- 使用标准 C++ 已有 24 年的向量有什么问题?
  • int n; cout&lt;&lt;"Length of array"; cin&gt;&gt;n; int a[n]; 这是设置数组长度的方法
【解决方案2】:

这是我一直在寻找的答案,我在这里发布它可能被其他人使用。

#include <iostream>

using namespace std;

int get_numbers(int a[]) {
    int i = 0;
    while (a[i] >= 0) {
        cout<<"please enter a number: ";
        cin >> a[i];
        if (a[i] < 0)
            break;
        i++;

    }
    return i;
}

void print_stars(int n) {
    for (int i = 0; i < n; i++) {
        cout << "* ";
    }
    cout << endl;
}

void sort(int a[], int n) {
    for (int i = 0; i < n - 1; i++) {
        for (int j = 0; j < n - i - 1; j++) {
            if (a[j] < a[j + 1]) {
                int temp = a[j];
                a[j] = a[j + 1];
                a[j + 1] = temp;
            }
        }
    }
}

void print_sorted_numbers(int a[], int n) {
    for (int i = 0; i < n; i++) {
        cout << a[i] << " ";
    }
}

【讨论】:

    猜你喜欢
    • 2021-07-30
    • 1970-01-01
    • 2021-11-09
    • 2021-05-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-10-06
    相关资源
    最近更新 更多