数组c++获取值

Arrays C++ getting values

本文关键字:获取 c++ 数组      更新时间:2023-10-16

正在做一个练习,当用户输入他选择的值时,要打印出数组中数字的索引位置。

这是目前为止的代码,但不知道如何组织它来打印他们从数组列表中输入的数字的索引位置

#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]时,它是一个索引为01011元素数组。

所以当你在循环中有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++)