2017-08-22 79 views
1

我需要幫助。我有一個任務說:C++檢查整數是否在數組中

要求用戶鍵入10個整數的數組和整數v。該程序必須搜索如果v是在10個整數的數組。如果整數v在數組中或者「v不在數組中」,那麼程序寫入「v在數組中」,如果不是,則寫入「v不在數組中」。

我的代碼似乎很好,但它不能正常工作。請幫忙。

這裏是我的代碼:

#include <iostream> 
#include <conio.h> 
#include <stdlib.h> 
using namespace std; 

int main() { 
    const int size = 10; 
    int vars[size],temp = 0,v = 0; 
    int boolean = 0,choice; 
    string check = ""; 
    for(int x = 0; x<10; x++){ 
     cout<<"Enter 10 Numbers: "; 
     cin>>vars[x]; 
    } 

    do{ 
     cout<<"Enter V variable :"; 
     cin>>v; 

     for(int x = 0; x <10; x++) 
     { 
      temp = vars[x]; 
      if(temp == v){ 
       check = "v is in the array"; 
      } 
      else{ 
       check = "v is not in the array"; 
      } 
     } 
     cout<<check; 
     cout<<"\nContinue ?"<<endl<<"[1]yes"<<endl<<"[2]no"<<endl; 
     cin>>choice; 
     system("cls"); 
     for(int x = 0; x<10;x++){ 
      cout<<"index" <<x<<" = "<<vars[x]<<endl; 
     } 
    } while(choice != 2); 
    return 0; 
} 
+5

歡迎來到Stack Overflow!這聽起來像你可能需要學習如何使用調試器來遍歷代碼。使用一個好的調試器,您可以逐行執行您的程序,並查看它與您期望的偏離的位置。如果你打算做任何編程,這是一個重要的工具。進一步閱讀:[如何調試小程序](http://ericlippert.com/2014/03/05/how-to-debug-small-programs/) – NathanOliver

+0

和https://stackoverflow.com/questions/2069367/如何調試使用gdb – Yunnosch

+0

'{檢查=「v在陣列中」;打破; }' –

回答

0

您正在運行的循環10次。即使第一個數字是您正在尋找的答案,循環的第二次迭代將重寫您的「檢查」變量。

要麼斷開if以便退出循環或更改邏輯。

你看起來像一個初學者,所以請參閱this閱讀更多關於break語句。

2

儘管沒有任何IO錯誤檢查,但您應該根據完成的迭代建立消息傳遞價值,而不是基於每次迭代。

此:

for(int x = 0; x <10; x++) 
    { 
     temp = vars[x]; 
     if(temp == v){ 
      check = "v is in the array"; 
     } 
     else{ 
      check = "v is not in the array"; 
     } 
    } 

    cout << check; 

將執行循環迭代size次不管是什麼,重新check在每次迭代,只打印最後迭代結果。你需要的是這樣的:

int x = 0; 
    for(; x <size && vars[x] != v; ++x); 

    if (x == size) 
     std::cout << v << " is NOT in the array"; 
    else 
     std::cout << v << " is in the array"; 

或者更好的是,使用標準庫,並停止重新發明輪子:

auto it = std::find(std::begin(vars), std::end(vars), v); 
    if (it == std::end(vars)) 
     std::cout << v << " is NOT in the array"; 
    else 
     std::cout << v << " is in the array"; 
0

你的程序是正確的,除了最重要的事情是在你的循環時條件成功,意味着找到了數字V,您必須break n爲了不改變下一次迭代。所以儘快發現不要繼續迭代數組中斷的所有元素。

for(int x = 0; x <10; x++){ 
    if(vars[x] == v){ 
     check = "v is in the array"; 
     break;// You must add break to get out of the loop with `check = "v is in the array"`. 
    } 
    else{ 
      check = "v is not in the array"; 
     } 
    } 
+0

非常感謝您的幫助。我真的忘了打破。我需要休息 :) – arteezy