如何做数组

How to do array

本文关键字:数组 何做      更新时间:2023-10-16

我正在尝试学习如何编写数组代码。(我还是去年刚开始学习的编程初学者(我不知道我的代码出了什么问题。问题是从用户那里获取 5 个整数输入并将它们存储在一个数组中。再次要求用户提供一个数字。现在,告诉用户该数字是否存在于数组中。 但是我的代码无法识别我的其他代码。即使我输入了一个数组中不存在的数字,它仍然显示"它存在"。

int main(){
int num[4];
int i;
int comp;
cout<<"Please input 5 numbers: "<<endl;
for (i=0;i<=4;i++)
{
cin>>num[i];
}
cout<<"Now please input another number to compare: ";
cin>>comp;
if (num[i]=comp){
cout<<"The number you inputted is present in the array";
}
else {
cout<<"It is not present in the array";
}
}

问题是从用户那里获取 5 个整数输入并将它们存储在数组中。

让我们开始声明一个最多可容纳5个整数的数组。

int numbers[5] = {};
//         ^^^        This should be the size of the array, not the maximum index

从 C++11 开始,您可以使用适当的标准容器

std::array<int, 5> numbers{};

请注意,在这两个代码段中,我都初始化了这些数组。

现在,读取数组所有元素的循环可以写为

for (int i = 0; i < 5; ++i) {
//                ^
}

或者使用范围为

for (auto & number : numbers)
{ //      ^^^^^^^^  Loops through the array using `number` as a reference to each element 
std::cin >> number;
if (!std::cin) {
std::cerr << "An error occurred while reading.n";
break;
}
}

发布的循环也从 0 到 4(包含(,但该代码段中声明的数组只有4个元素,因此它是越界访问的,并且程序具有未定义的行为。

另一个问题是程序不检查

该数字是否存在于数组中

它只执行一个"检查",而不是循环:

if ( num[i] = comp) {     

num[i] = comp是一个赋值,而不是比较(你应该充分提高编译器警告级别(和数组外部元素的赋值(i现在的值为 5(。它是此赋值的结果,comp用作条件,这意味着只要comp不为 0,就会执行分支。

或者,至少,这是最有可能的结果,因为该赋值也是 UB,并且编译器可以生成它决定的任何代码,或者您的程序可能会由于访问越界而出现段错误。

#include "stdafx.h"
#include <iostream>

int _tmain(int argc, _TCHAR* argv[])
{
int num[4];
int i;
int comp;
int coo;
int flg=0;
std::cout<<"Please input four numbers: "<<"n";
for (i=0;i<=3;i++)
{
std::cin>>num[i];
}
std::cout<<"Now please input another number to compare: ";
std::cin>>comp;
for (i=0;i<=3;i++)
{
if (num[i]==comp){
flg = 1;      
break;
}
}
if (flg) {
printf("The number you inputted is present in the array.n","%s");
} else {
printf("It is not present in the arrayn", "%s");
}
std::cin>>coo;
return 0;
}

基本上,在将数组与要比较的数字进行比较时,您省略了遍历所有数组成员,我只是添加了循环,以便它遍历所有数组成员并将其与输入数字进行比较。