gpt4 book ai didi

c++ 检查整数是否在数组中

转载 作者:行者123 更新时间:2023-11-30 03:29:16 24 4
gpt4 key购买 nike

我需要帮助。我有一个任务说:

Asks the user to type 10 integers of an array and an integer v. The program must search if v is in the array of 10 integers. The program writes "v is in the array" if the integer v is in the array or "v is not in the array" if it's not.

我的代码看起来不错,但不能正常工作。请帮忙。

这是我的代码:

#include <iostream>
#include <conio.h>
#include <stdlib.h>
using namespace std;

int main () {
const int size = 10;
int vars[size],temp = 0,v = 0;
int boolean = 0,choice;
string check = "";
for(int x = 0; x<10; x++){
cout<<"Enter 10 Numbers: ";
cin>>vars[x];
}

do{
cout<<"Enter V variable :";
cin>>v;

for(int x = 0; x <10; x++)
{
temp = vars[x];
if(temp == v){
check = "v is in the array";
}
else{
check = "v is not in the array";
}
}
cout<<check;
cout<<"\nContinue ?"<<endl<<"[1]yes"<<endl<<"[2]no"<<endl;
cin>>choice;
system("cls");
for(int x = 0; x<10;x++){
cout<<"index" <<x<<" = "<<vars[x]<<endl;
}
} while(choice != 2);
return 0;
}

最佳答案

尽管缺少任何 IO 错误检查,但您应该根据已完成的迭代而不是每次迭代来建立消息传递 check 值。

这个:

    for(int x = 0; x <10; x++)
{
temp = vars[x];
if(temp == v){
check = "v is in the array";
}
else{
check = "v is not in the array";
}
}

cout << check;

无论如何都会执行循环迭代 size 次,每次迭代都会重置 check 并且只打印最后 次迭代结果。你想要的是这样的:

    int x = 0;
for(; x <size && vars[x] != v; ++x);

if (x == size)
std::cout << v << " is NOT in the array";
else
std::cout << v << " is in the array";

或者更好的是,使用标准库并停止重新发明轮子:

    auto it = std::find(std::begin(vars), std::end(vars), v);
if (it == std::end(vars))
std::cout << v << " is NOT in the array";
else
std::cout << v << " is in the array";

关于c++ 检查整数是否在数组中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45825818/

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