RE,两关

P2249 【深基13.例1】查找

jingliang_youxi @ 2024-10-10 10:29:44

#include <bits/stdc++.h>
using namespace std;
const int N = 1e8;
int l, r, n, m, a[N], b, h;

int a1(int a[], int l, int r, int x) {
    if (l == r) {
        if (a[l] == x)
            return l;
        else
            return -1;
    }
    int m = (l + r) / 2;
    if (x <= a[m]) {
        a1(a, l, m, x);
    } else {
        a1(a, m + 1, r, x);
    }
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i <= m; i++) {
        cin >> b;
        cout << a1(a, 1, n, b) << " ";
    }
    return 0;
}

by queenbee @ 2024-10-10 10:37:17

@jingliang_youxi int函数记得return

#include <bits/stdc++.h>
using namespace std;
const int N = 1e8;
int l, r, n, m, a[N], b, h;

int a1(int a[], int l, int r, int x) {
    if (l == r) {
        if (a[l] == x)
            return l;
        else
            return -1;
    }
    int m = (l + r) / 2;
    if (x <= a[m]) {
        return a1(a, l, m, x);
    } else {
        return a1(a, m + 1, r, x);
    }
}

int main() {
    cin >> n >> m;
    for (int i = 1; i <= n; i++) {
        cin >> a[i];
    }
    for (int i = 1; i <= m; i++) {
        cin >> b;
        cout << a1(a, 1, n, b) << " ";
    }
    return 0;
}

by 呆呆的她啊 @ 2024-10-10 11:08:38

@jingliang_youxi 有返回值的函数不返回数值 会报错以及出现未定义行为


by craftmine @ 2024-10-11 10:58:49

@jingliang_youxi 非void必须return


|