初学者数组的问题,C++

Problems with Beginner Arrays, C++

本文关键字:C++ 问题 数组 初学者      更新时间:2023-10-16

赋值需要三个函数。用户输入数字 0-9,直到输入 10,这将停止输入,并计算每个数字,然后输出每个数字中有多少个已计数。仅当用户为其输入数字时,它才应输出。

我唯一的问题是,对于数组中用户不使用的每个元素,Xcode 都会将其计为 0,因此最终输出具有异常大量的零。其他一切正常。

这是我的代码

#include <iostream>
using namespace std;
// counter function prototype
void count(int[], int, int []);
// print function prototype
void print(int []);
int main()
{
    // define variables and initialize arrays
    const int SIZE=100;
    int numbers[SIZE], counter[10], input;
    // for loop to set all counter elements to 0
    for (int assign = 0; assign < 10; assign++)
    {
        counter[assign]=0;
    }
    // for loop to collect data
    for (int index=0 ; input != 10 ; index++)
    {
        cout << "Enter a number 0-9, or 10 to terminate: ";
        cin >> input;
        // while loop to ensure input is 0-10
        while (input < 0 || input > 10)
        {
            cout << "Invalid, please enter 0-9 or 10 to terminate: ";
            cin >> input;
        }
        // if statements to sort input
        if (input >= 0 && input <=9)
        {
            numbers[index] = input;
        }
    }
    // call count function
    count(numbers, SIZE, counter);
    // call print function
    print(counter);
    return 0;
}
// counter function
void count(int numbers[], int SIZE, int counter[])
{
    // for loop of counter
    for (int index = 0 ; index < 10 ; index++)
    {
        // for loop of numbers
        for (int tracker=0 ; tracker < SIZE ; tracker++)
        {
            // if statement to count each number
            if (index == numbers[tracker])
            {
                counter[index]++;
            }
        }
    }
    return;
}
// print function
void print(int counter[])
{
    // for loop to print each element
    for (int index=0 ; index < 10 ; index++)
    {
        // if statement to only print numbers that were entered
        if (counter[index] > 0)
        {
            cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
        }
    }
    return;
}

你所说的"XCode count[ing] as a 0"实际上只是未初始化的值。鉴于您决定将用户的输入限制为 0-9,解决此难题的一种简单方法是,在调整数组大小后立即循环访问数组并将每个值设置为 -1。

此后,当用户完成输入时,不要只cout每个值,而只需使用如下所示的条件打印它:

if (counter[index] != -1)
{
    cout << "You entered " << counter[index] << ", " << index << "(s)" << endl;
}

请注意,这种用例更适合链表或向量之类的东西。就目前而言,您没有做任何事情来调整数组大小或防止溢出,因此如果用户尝试输入超过 100 个数字,您会遇到严重的问题。

首先,这不是对你的确切问题的答案,而是关于如何以更简单的形式编写代码的建议。

我不会为你写这个,因为这是一个任务,而且相当简单。就编码而言,看起来您对事情有很好的处理。

考虑一下:

您需要允许用户输入 0-10,并计算所有 0-9。数组有索引,数组 10 的整数将保存您按索引计数的 10 个数字。现在你只有一些空的int坐在那里,所以为什么不用它们来计数呢?

代码提示:

++numbers[input];

第二个提示:不要忘记将所有内容初始化为零。