簡體   English   中英

數組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] ,它是11元素的數組,其索引是010

因此,當您的循環中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 >> num; numbers[x] = num; 做到這一點。 你可以去cin >> numbers[x]; 直。 如果運行循環,則可以連續輸入多個數字,例如:

for( x = 0; x < 11; ++x )
    cin >> numbers[x];

您沒有檢查給定數字在哪個索引中。 該聲明:

numbers [x] = {num};

只需將num分配給數組x-th項目。 在您的情況下, x已初始化為零。 因此,數組的第一項設置為num

cout << numbers [x];

總是打印數組的第一項。

您可以通過替換謊言來解決此問題

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;
}

1-該程序找不到索引!! 為了找到索引,您應該在數組上循環並比較array [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];    }

您可以循環查找自己的索引,也可以使用std::find

int* pos = find(&numbers[0], &numbers[11], num);
if (pos == &numbers[11]) {
    cout << "not found\n";
} else {
    cout << (pos - &numbers[0]) << endl;
}

另外,你應該改變

for (int i = 0; i <= 11; i++)

for (int i = 0; i < 11; i++)

避免數組索引超出范圍。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM