当问题被执行时,它工作正常,说明模式是 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;
}
最佳答案
在测试软件时,您希望拥有包含所有不同分支的测试用例。现在,您仅演示了代码在给定输入数组存在唯一的最高频率元素时有效。
您的教授还希望您在最高重复次数不唯一时进行测试。
这通常称为极端情况。
教授的措辞很不幸。 exception 这个词在 C++ 中有特定的含义,但事实并非如此……除非您的指令是在最高重复次数不唯一时实际抛出异常。
好的附加测试用例是:
长度为零的数组
{}
长度为1的数组
{ 7 }
最高重复次数的双向并列
{ 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 }
如果您的代码对所有这些情况都给出了正确的结果,您将非常有信心它对所有输入都是正确的。
关于c++ - 没有模式有异常(exception)是什么意思? (数组中出现次数最多的数)?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27280613/