c++ - 返回 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。代码运行良好,但没有返回任何值。请帮忙。
解决方案
改变这个
bin_search(n, arr, k);
像这样
cout << "element found at index " << bin_search(n, arr, k) << endl;
正如丘里尔所说,返回一些东西与打印一些东西不同。如果你想打印一些东西,请使用cout <<
. 如果你想返回一些东西,请使用return
. 如果你想要两者都使用。
如果你想在一个函数中计算一些东西然后打印结果,main
那么你需要从 调用函数main
,从函数返回值,然后在 中打印返回的值main
。
推荐阅读
- java - 您好,我在 Eclipse 中用于 Selenium 测试的代码有问题
- asp.net-core-3.1 - 如何从 Utils 类的 GetValue 方法传递 Ilogger 引用
- python - x轴为字符串时如何使python matplotlib显示x轴坐标(右上角)
- powershell - 如何从 ADFS 属性中删除双重条目
- google-chrome - 有没有办法调试 chrome 请求排队的原因?
- java - 在 RecyclerView 适配器中使用 ViewModel 的实时数据
- oracle - Oracle Apex 如何动态更改文本输入的字体
- php - 使用 Imagick php 获取图像的主色
- asp.net-core-mvc - 单独的类库中的 DBcontext 类和 Asp.net 核心 webapi 应用程序是一个单独的项目
- apache - 从 Windows 上的 Apache Web 服务器连接到 Azure AD