Qusetion:
題目描述:
輸入一個數n,然後輸入n個數值各不相同,再輸入一個值x,輸出這個值在這個數組中的下標(從0開始,若不在數組中則輸出-1)。
輸入:
測試數據有多組,輸入n(1<=n<=200),接着輸入n個數,然後輸入x。
輸出:
對於每組輸入,請輸出結果。
樣例輸入:
4
1 2 3 4
3
樣例輸出:
2
思路:
1.利用input函數分別存儲n值和由n產生的數組以及x的值
2.通過遍歷對比的方式,確定要搜索的x值的位置
3.利用mark標記在list中是否存在於x匹配的值,如不存在則輸出-1
Code[Python]
n=int(input())
listword=[]
for i in range(n) :
listword.append(int(input()))
x=int(input())
mark=False
count=-1
for j in listword:
count=count+1
if x==j:
mark=True
print(count)
break
if mark==False:
print(-1)
Code[C++]
#include<cstdio>
const int maxn=210;
int a[maxn];
int main(){
int n,x;
while (scanf("%d",&n)!=EOF){
for (int i=0;i<n;i++){
scanf("%d",&a[i]);
}
scanf("%d",&x);
int k;
for (k=0;k<n;k++){
if(a[k]==x){
printf("%d\n",k);
break;
}
}
if (k==n){
printf("-1\n");
}
}
return 0;
}
反思:
在python代碼中,並沒有將n的定義域考慮進去