2017-08-14 31 views
-7
#include <iostream> 

float x[10], k; 
int n, i; 

cout<<"N= "; cin>>n; 

for (i=0; i<n; i++){ 
    cout<<"x["<<i<<"]= "; 
    cin>>x[i]; 
} 

cout<<"Array's elements: "; 
for (i=0; i<n; i++) 
    cout<<x[i]<<", "; 

cout<<endl<<"K= "; cin>>k; 
for(i=0; i<n; i++) 
    if(x[i]!=k){ 
     cout<<endl<<"K doesn't exist in array."; 
     cout<<endl<<"K= "; cin>>k; 
    } 

我試圖找到,如果在數組中存在的元素,如果它不存在,我想重新鍵入元素,重複整個陣列進行檢查。 我從一開始就沒有得到它(i = 0)。找到,如果在C++數組存在一個元素

+6

這是相當明顯。在檢查第一個元素之後,你不能聲明元素不在數組中。 – LogicStuff

+3

['std :: find'](http://en.cppreference.com/w/cpp/algorithm/find) – CoryKramer

+0

你寫的是一個檢查*所有元素都是你正在尋找的元素。如果你不想使用標準算法(你真的應該使用標準算法),你需要使用一個標誌來查看它們是否匹配。 –

回答

2

有一個在頭<algorithm>稱爲std::find標準功能:

#include <iostream> 
#include <algorithm> 

int main() { 
    int myarray[6]{10, 4, 14, 84, 1, 3}; 

    if (std::find(std::begin(myarray), std::end(myarray), 1) != std::end(myarray)) 
     std::cout << "It exists"; 
    else 
     std::cout << "It does not exist"; 
    return 0; 
} 

Ideone

3

在標準庫中有一個完美的功能 - std::any_of - 如果你想知道的只是某種東西存在。

如果您還需要訪問找到的元素,則有std::findstd::find_if

如果你想知道存在多少次,標準庫已經覆蓋了std::countstd::count_if

+1

我爲學校做了一些練習,但我們還沒有學習過這種練習。但我會嘗試。 謝謝! – Nick28

-2

設法使一個新的變量稱爲CNT和使用它像這樣 -

for(i=0; i<n; i++) 
    if(x[i]==k){ 
     ++cnt; 

    } 
if (cnt==0) 
    cout << "k has not occured"; 
else 
    cout<<"k has occured"<<cnt<<"times"; 
+1

你不需要統計它們全部。 – LogicStuff

+0

這有時候可以檢查一個字母或句子中發生了多少次字母 – Kadhem

+0

這個工作有一次,但如果我想再次檢查,我需要重複並重復此代碼...(你明白了) – Nick28

相關問題