数组c++获取值
Arrays C++ getting values
正在做一个练习,当用户输入他选择的值时,要打印出数组中数字的索引位置。
这是目前为止的代码,但不知道如何组织它来打印他们从数组列表中输入的数字的索引位置
#include <iostream>
using namespace std;
int main()
{
int numbers [11] = {5, 2, 11, 6, 33, 756, 32, 0, 1, 31, -1,};
int num = 0;
int x = 0;
cout << "List:" ;
for (int i = 0; i <= 11; i++)
{
cout << numbers [i] << ", ";
}
cout << endl;
cout << "Enter a number from the list to find its position: ";
cin >> num;
numbers [x] = {num};
cout << numbers [x];
}
基本上它现在所做的就是打印你输入的数字而不是它在数组中的位置....
如何从用户输入
首先,这是未定义行为,
for (int i = 0; i <= 11; i++) // will iterate from 0 to 11
数组范围从0
开始,所以如果你想循环通过它或需要到最后一个元素,你应该访问Array[MaxNum-1]
。所以你应该使用
for (int i = 0; i < 11; i++) // will iterate from 0 to (11-1)
现在你又有疑问了::
你应该遍历整个数组,找到你的数字,然后打印索引如下::
int nIndex = -1 ;
for (int i = 0; i < 11; i++ )
{
if ( numbers[i] == num )
{
nIndex = i ;
break ;
// Or to end the loop, you can set i = SomeValueToBreakTheCondition
// ex., i = 11
}
}
if( nIndex == -1 )
{
std::cout << Element Not Found ;
}
else
{
std::cout << "Element Found Out Index::" << nIndex ;
}
当您写入int numbers[11]
时,它是一个索引为0
到10
的11
元素数组。
所以当你在循环中有i <= 11
;最后一次循环迭代读取超出数组末尾的内容,导致未定义的行为。将其更改为i < 11
,或者更好的i < sizeof numbers / sizeof numbers[0]
,如果您认为它看起来不错,您可以将其包装在宏中。
numbers [x] = {num};
最好写成numbers[x] = num;
。无论如何,你然后去:cout << numbers[x]
,它完全按照你说的做:它把数字放在x
索引的位置,你刚刚存储了num
。
如果你想输出位置,那么执行cout << x;
。
如何从用户输入
中输入值到数组中?
你已经这么做了,cin >> num; numbers[x] = num;
也这么做了。你可以直接去cin >> numbers[x];
。如果运行循环,则可以在一行中输入多个数字,例如:
for( x = 0; x < 11; ++x )
cin >> numbers[x];
1-这个程序没有找到索引!!为了找到索引,你应该对数组进行循环并比较数组[i]和x
for(int i = 0 ; i < 10 ; i++)
{
if(number[i] == x)
{
// do what you want with index i
}
}
2-对于输入数组,您可以这样做
for(int i = 0 ; i < 10 ; i++) { cin >> numbers[i]; }
您没有检查给定数字是哪个索引。声明:
numbers [x] = {num};
只是将num
赋值给数组的x-th
项。在您的示例中,x
已初始化为零。因此,数组的第一项被设置为num
和
cout << numbers [x];
总是输出数组的第一项。
你可以通过替换lies
来解决这个问题numbers [x] = {num};
cout << numbers [x];
for (int i = 0; i < 11; ++i )
{
if ( numbers[i] == num )
{
cout << i << endl;
break;
}
}
if ( i == 11 )
{
cout << "Number not found" << endl;
}
您可以自己创建一个循环来查找索引,也可以使用std::find
:
int* pos = find(&numbers[0], &numbers[11], num);
if (pos == &numbers[11]) {
cout << "not foundn";
} else {
cout << (pos - &numbers[0]) << endl;
}
另外,你应该修改
for (int i = 0; i <= 11; i++)
for (int i = 0; i < 11; i++)
- C++为构建时间获取QDateTime的可靠方法
- lambda参数转换为constexpr技巧,然后获取带链接的数组
- 如何使用 < 和 > 命令获取 c++ 中的输入和输出?
- 使用指针从C++中的数组中获取最大值
- 如何获取std::result_of函数的返回类型
- 如何在openssl-ecc中获取十六进制格式的私钥
- 使用Unreal C++获取VR耳机的世界位置/方向
- 获取日期异步信号安全吗?如果在信号处理程序中使用,它会导致死锁吗
- 从C字符串中获取奇怪的字符串长度
- 为什么我的for循环不能正确获取argv
- 从python中调用C++函数并获取返回值
- 如何获取一个数字的前3位
- 获取字符串的长度并将其分配给数组
- 无法获取菜单选择以运行函数.C++
- 数组长度,为什么从命令行获取时不能使用它?
- Boost Spirit,获取迭代器内部语义动作
- 尝试通过OCI例程从Oracle获取blob数据,但出现错误:ORA-01008:并非所有变量都绑定
- 具有默认值的引用获取函数
- xmake总是报告:错误:无法获取cxx的程序,为什么
- 在c++中获取大文件的大小