1
所以我的程序应该使用一个5大小的数组来存储输入的整数。如果它是一个重复的整数,它将不会被存储到数组中。如何忽略数组中的0并打印出唯一的数字
这里的问题是我的数组中会有0的无限期,因为我初始化的大小为5.我只需要输出唯一的数字我该怎么做?
我注意到的一件事是,没有我的无符号整型位置;每当我输入一个重复的整数,它会跳过索引;
例如 array [0] = 10,array [1] = 10 // duplicate,array [2] = 20 //输入20,它应该已经存储到数组[1]中,但它没有。 所以,我只有在不重复的情况下才会增加位置,以确保在输入重复项时不会跳过索引。
有没有什么我可以做或做不同的方法来得到我的结果?
代码:
#include <iostream>
#include <iomanip>
#include <array>
using namespace std;
const unsigned int MIN_VALUE = 10;
const unsigned int MAX_VALUE = 100;
const size_t arraySize = 5;
array <int, arraySize> numberArray = {};
template<size_t size>
bool isDuplicate(array<int, size> array, int value)
{
for (unsigned int i = 0; i < array.size(); i++)
{
if (value == array[i])
{
return true;
}
}
return false;
}
int main()
{
unsigned int input;
unsigned int position = 0;
for (unsigned int i = 0; i < arraySize; i++)
{
cout << "Enter # " << (i + 1) << " : ";
cin >> input;
if (input < MIN_VALUE || input > MAX_VALUE)
{
cout << "The number entered is not in valid range of 10 to 100" << endl;
--i;
}
else if (!isDuplicate(numberArray, input))
{
numberArray[position] = input;
position++;
cout << "The number: " << input << " is unique\n" << endl;
}
}
}
谢谢!
事情的要求是,当用户输入一个重复的号码时,它会忽略它,所以它几乎仍然递增外部循环以提示用户输入**下一个#**。例如:输入#1:10,输入#2:10,然后输入#3:20 .....它不会减少它,所以我最初的问题是,会有一点数组的索引根本不使用,因此它的0.我只需要打印出唯一的数字而不是0。谢谢! –
nevemind ...我知道了。我对于打印整个阵列的方式太在意,但我忘记了位置是跟踪我正在使用的元素,我可能只是将位置打印出来。 Ahahaha感谢您的帮助!真的很感激它。 –
如果排序对你无关紧要,你可以看看'std :: unordered_set'这可能已经用更少的代码行解决了你的问题:http://www.cplusplus.com/reference/unordered_set/unordered_set/ ?千瓦= unordered_set。 无论如何,不客气。 ;) – WillCroPoint