0
此代碼嘗試在硬編碼值的5x5矩陣中搜索目標值(項目)。它向用戶查詢要搜索的值。問題是,當我運行代碼時,它會告訴我「發現項目!」不管用戶輸入。此外,它似乎在重複用戶輸入。例如,當我使用「87」作爲用戶輸入時,這是我的輸出:不需要的輸出重複和矩陣搜索問題
您希望搜索什麼值? 878787找到了!
我對C++相當陌生,所以原諒我,如果我做了一些愚蠢的事情。代碼如下:
#include <iostream>
#include <algorithm>
#include <array>
using namespace std;
int main()
{
int target;
int flag;
int mat[5][5]= //hardcoded the matrix data
{
{1,2,3,4,5},
{6,7,8,9,10},
{11,12,13,14,15},
{16,17,18,19,20},
{21,22,23,24,25}
};
cout<<"What is the value you'd like to search for? ";
cin>>target;
for(int x=0;x<5;x++)
{
for(int y=0;y<5;y++)
{
if (mat[x][y]==target)
{
flag=1;
break;
}
else
{
//do nothing
}
}
}
if(flag == 1)
{
cout<<"Item found!";
}
else
{
cout<<"Item not found.";
}
return 0;
}
你for循環中的所有'<='都需要是<<'s。否則你有未定義的行爲。 – NathanOliver
正如Nathan指出的那樣,您正在對陣列進行無效訪問。可能發生的情況是,程序正在讀取其中一個訪問中的'target'變量,因此總是「找到該項目」。順便說一下,你的'break'語句只能從內部循環中出來,而不能從外部循環中出來。所以通過每次迭代設置'flag = 0',即使你修復了Nathan指出的問題,你仍然會遇到問題。 – aslg
你可以失去其他部分,也不需要將標誌設爲0 –