无模式例外是什么意思?(数组中出现次数最多的数字)

What does it mean to have an exception for no mode? (The number that occurs the most in an array)?

本文关键字:数字 模式 是什么 意思 数组      更新时间:2023-10-16

当问题被执行时,它正常工作,表明模式为3。教授要求"程序应该考虑没有"模式"发生的"异常"——数组中没有值出现多次。问题是我不明白它在问什么。我无法开始这样的事情。

void showArray(const int[], int); 
void showMode(int [], int);
using namespace std;
int main()
{
    const int Size = 11; //size of the array
    int test[Size] = {1, 2, 3, 3, 3, 2, 2, 1, 3, 4, 5}; //elements of the array
    cout << "The Numbers in the Array are: n";
    showArray(test, Size); //displays the array in its original order
    showMode(test, Size);
    return 0;
}
void showArray(const int arr[], int Size) 
{
    for(int count = 0; count < Size; count++)
        cout << arr[count] << " ";
    cout << endl;
}
void showMode(int test[], int Size)
{
    int counter = 1;
    int max = 0;
    int mode = test[0];
    for(int pass = 0; pass < Size - 1; pass++)
    {
        if(test[pass] == test[pass + 1])
            {
                counter++;
                if(counter > max)
                {
                    max = counter;
                    mode = test[pass];
                }
            }
        else
            counter = 1;
    }
    cout << "The Mode of the Array is: " << mode << endl;
}

在测试软件时,您希望拥有采用所有不同分支的测试用例。 现在,您只演示了当给定输入数组存在唯一的最高频率元素时,代码才有效。

您的教授还希望您在最高重复次数不是唯一的时进行测试。

这通常称为极端情况。

教授的措辞是不幸的。 例外这个词在C++中具有特定的含义,这不是它......除非您的指示是在最高重复计数不唯一时实际引发异常。

好的附加测试用例是:

  • 长度为零的数组

    {}
    
  • 长度为一的数组

    { 7 }
    
  • 2 向并列,重复次数最高

    { 1, 2, 3, 2, 1 }
    { 1, 1, 2, 3, 3 }
    
  • N 路并列,用于最高重复计数

    { 1, 3, 5, 4, 2 }
    
  • 领带被第一个元素破坏

    { 2, 6, 3, 2, 4, 5, 2, 6, 9 }
    
  • 领带被最后一个元素破坏

    { 6, 3, 2, 4, 5, 2, 6, 2 }
    
  • 其他元素具有更长的"运行">

    { 5, 2, 6, 3, 2, 4, 4, 5, 2, 6, 9 }
    

如果您的代码为所有这些情况提供了正确的结果,您将有很高的置信度,即它适用于所有输入