gpt4 book ai didi

c++ - 检查用户输入时数组元素值是否已经存在

转载 作者:行者123 更新时间:2023-11-28 07:17:42 24 4
gpt4 key购买 nike

如何检查数组是否已经包含一个值?

例如,输入:1输出:1

输入:1错误!:数字已存在

输入:2输出:2

当用户输入已经存在于数组中时,它会显示错误并要求他们重新输入,直到他们输入不同的值。当输入不同的值时,该值将被添加到数组中。如果输入的值与任何元素值相同,则不会将其添加到数组中。

int num[5], temp;
bool val = true, existed = false;

for(int i = 0; i < 5; i++){
val = true;

while(val){

cout << "\nPlease enter a number:";
cin >> temp;

for(int x = 0; x < 5; x++){
if(temp == num[x]){
existed = true;
}
}

if(existed){
cout << "Number existed";
} else {
num[i] = temp;
cout << "Your number" << num[i];
val = false;
}
}

}

最佳答案

您可以编写一个简短的函数来进行检查:

bool alreadyExists(int *array, int array_size, int value)
{
for (int i = 0; i < array_size; i++)
if (array[i] == value)
return true; // we found the same value, return true

return false; // if we get here we have not found it
}

调用它

int input = 1;
if alreadyExists(num, 5, input)
{
printf("already exists\n");
}
else
{
printf("Ok to add...");
}

关于c++ - 检查用户输入时数组元素值是否已经存在,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19971832/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com