我希望我的数组输入使得它不能具有两次相同的数字: 然而,这将有一个输出 "值存在请重新输入:&#34 ;; 两次。我如何检查它是否是唯一的,如果之前已经初始化,只显示一次?
int main(){
int arr_size = 10;
int value;
int aArray[10];
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
cin>>value;
for(int j=0;j<arr_size;j++){
if(value == aArray[j])
{
cout<<"value exist please re enter: ";
cin>>value;
}
else{
aArray[i] = value;
}
}
}
}
答案 0 :(得分:2)
更改为:
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
while(1) { //You must keep reading until you have read a valid value
cin>>value;
bool alreadyPresent = false;
for(int j=0;j<i;j++){ //You only have to check against already inserted values!
//Before you were checking against uninitialized values!!
if(value == aArray[j])
{
alreadyPresent = true;
break; //I don't need to further iterate the array
}
}
if (alreadyPresent)
cout<< std::endl << value exists, please re enter: ";
else
break; //I can proceed with the next value, user has not to reenter the value
}
aArray[i] = value;
std::cout << std::endl; //next line...
}
替代:
for(int i=0;i<arr_size;i++)
{
cout<<"enter value of slot"<<i+1<<": ";
bool alreadyPresent;
do { //You must keep reading until you have read a valid value
cin>>value;
alreadyPresent = false;
for(int j=0;j<i;j++){ //You only have to check against already inserted values!
//Before you were checking against uninitialized values!!
if(value == aArray[j])
{
alreadyPresent = true;
cout<< std::endl << value exists, please re enter: ";
break; //I don't need to further iterate the array
}
}
} while (alreadyPresent);
aArray[i] = value;
std::cout << std::endl; //next line...
}