c++ - 如何将数据输入数组并通过函数打印出来?

标签 c++ arrays algorithm function user-input

我正在尝试将数据输入到数组,然后使用函数打印它们,但我不确定如何组织代码。

#include <iostream>
using namespace std;

void showGrade(double grade[], int size);

int main()
{
    double grade[];
    int size;

    for (int i = 0; i < size; i++) 
    {
        cout << "Please enter the number of grade" << endl;
        cin >> size;
    }

    showGrade(grade, size);
    return 0;
}

void showGrade(double grade[], int size)    //How many grade we have
{
    for (int counter = 0; counter < size; counter++) 
    {
        cout << "Please enter your grades: " << endl;
        cin >> grade[counter];
        cout << "Here are your grades: " << endl;
    }
}

我希望看到我输入了多少个成绩,然后显示它们。

2019 年 8 月 28 日更新

我想出了如何在 main 函数中成功地做到这一点。但我真正想要的是将它们放在一个单独的函数中。我的新代码在函数调用时有错误,类型名称是不允许的,需要一个 ')'。我如何让它发挥作用?

#include <iostream>
using namespace std;

void showGrades(double ar[], int size);

int main()
{
    double ar[20];
    int size;

    showGrades(double ar[size], int size);

    system("pause");
    return 0;
}

void showGrades(double ar[], int size) {
    cout << "Please enter the number of grade "; // array size
    cin >> size;
    cout << "Please enter your grades " << endl;
    for (int i = 0; i < size; i++) {
        cin >> ar[i];
    }

    cout << "The grades you entered are: " << endl;

    for (int i = 0; i < size; i++) {
        cout << ar[i] << endl;
    }
}

最佳答案

  1. 首先,你需要使用标准容器 <强> std::vector 而不是 double grade[];,因为你想要一个可变长度的 根据用户输入排列。

  2. 其次,您在

    中使用了未初始化的 size 变量
    for (int i = 0; i < size; i++) 
    

    因此它将使用垃圾值进行初始化。你不需要 for-loop

一个好的开始是:

#include <iostream>
#include <vector>    // std::vector
void showGrade(std::vector<double>& grade)
//            ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ -> pass the vector by ref, as the grades should be inseted to the it
{
    // the logic
}

int main()
{
    int size;
    std::cout << "Please enter the number of grade" << endl;
    std::cin >> size;

    std::vector<double> grade;
    grade.reserve(size); // reserve memory for unwanted re-allocations

    showGrade(grade);
    return 0;
}

在阅读了更多有关 std::vector 的内容后,我将其留给您完成。

此外,不要使用 using namespace std; 进行练习。阅读更多: Why is "using namespace std;" considered bad practice?

关于c++ - 如何将数据输入数组并通过函数打印出来?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57615663/

相关文章:

java - 什么时候不使用 java8 流?

c# - 数组指针线程安全

algorithm - 存储同步数据的分布式算法

algorithm - 我的贪心算法有缺陷吗?

c++ - 在 C++ 中将字母转换为数字

c++ - Qt 从文件中打开图像 - 如何知道图像大小

c++ - 涉及 iostream 和 wstring 的奇怪 C++ 行为

c++ - 适用于 Windows Mobile 的 OpenGL ES 2.0 SDK

c# 从udp服务器字节到字符串

algorithm - 如何使用 MATLAB 找到两个 Blob (轮廓/闭合曲线)之间的最短路径?