首页 > 解决方案 > 返回 x; 在 C++ 中没有返回整数值

问题描述

#include <iostream>
using namespace std;

//binary search algo
int bin_search(int n, int a[], int k){ // k is the input value, n is the size of array.

    int s = 0;
    int e = n - 1;
    int m;
    while (s <= e){ // runs while s <= e cuz if s > e, the element doesn't exist
        m = (s + e) / 2;

        if (a[m] == k){
            // mid array ele equals k then we're done, returns mid array index value
            return m;
        }
        else if (a[m] < k){ // if mid array value is smaller than k, array before it is rejected
            s = m + 1;
        }
        else{
            e = m - 1; // if mid array value is larger than k then array after it is rejected.
        }
    }
    return -1;
}

int main(){

    int n, arr[3000];
    cout << "how big a sorted array do you want?";
    cin >> n; 

    cout << "enter yer sorted array: " << endl;
    for(int i = 0; i < n; i++){
        cin >> arr[i];
    }

    int k;
    cout << "which element do you want to find?";
    cin >> k;
    bin_search(n, arr, k);

    return 0;    
}

我编写此代码以返回输入值的索引,或者如果数组中不存在所述整数,则返回 -1。代码运行良好,但没有返回任何值。请帮忙。

标签: c++

解决方案


改变这个

bin_search(n, arr, k);

像这样

cout << "element found at index " << bin_search(n, arr, k) << endl;

正如丘里尔所说,返回一些东西与打印一些东西不同。如果你想打印一些东西,请使用cout <<. 如果你想返回一些东西,请使用return. 如果你想要两者都使用。

如果你想在一个函数中计算一些东西然后打印结果,main那么你需要从 调用函数main,从函数返回值,然后在 中打印返回的值main


推荐阅读