如何做数组
How to do array
我正在尝试学习如何编写数组代码。(我还是去年刚开始学习的编程初学者(我不知道我的代码出了什么问题。问题是从用户那里获取 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;
}
基本上,在将数组与要比较的数字进行比较时,您省略了遍历所有数组成员,我只是添加了循环,以便它遍历所有数组成员并将其与输入数字进行比较。
相关文章:
- 如何做数组
- 我正在尝试解决一个需要数组总和值但代码不起作用的问题,我想做这样的事情
- 创建整数的 2D 数组,该数组将使用两个函数用随机数填充矩阵.我做错了什么?
- <<(按位左移)在 Swift 中的数组上做什么?
- 将const int std ::数组的n元素复制到int矢量中.怎么做
- 如果 strlen 在 char 数组之间遇到空格,它会怎么做
- 在C 中,对2D数组的增量是什么?函数断言(0)做什么?
- inheritance:如何用相同的函数生成一个不同类的数组,这些类在C++中做不同的事情
- Java使用数组的速度是C++中std::vector的8倍.我做错了什么
- 数组有效,而矢量无效。我做错了什么?
- 如何正确地将std::字符串转换为无符号char[]数组*.我觉得我做错了,有人给我指明了正确的方向
- 动态对象数组在C++和Java中有何不同?
- 数组 + int 作为一个参数做什么
- 创建动态数组后,"i"变量不知从何而来
- 我应该怎么做才能初始化结构数组
- 我的动态数组模板类正在做奇怪的事情
- 这些数组类型有何不同
- 带有1个参数的C++2D数组索引(为什么这样做?)
- 在C++中,当我初始化类对象数组时,当我想通过构造函数初始化类成员时,我应该怎么做
- 我应该怎么做才能获得"动态"数组的大小?