c++ - 如何正确声明变量
问题描述
我应该编写一个包含 20 个整数的数组的程序,它需要调用一个使用线性搜索算法来定位其中一个值的函数和另一个使用二分搜索算法来定位相同值的函数。这两个函数都需要计算它进行的比较次数并显示它们。
我需要使用以下原型:
int linearSearch(const int arr[], int size, int value)
int binarySearch(const int array[], int numElems, int value)
编译程序后,我会收到一条警告,指出
变量 'position1' 已设置但未使用”。
我已经初始化了变量,但我找不到问题。
//Function for linear search
int linearSearch(const int arr[], int size, int value)
{
int index = 0;
int position1 = -1;
bool found = false;
int counter1 = 0;
while( index < size && !found)
{
if(arr[index] == value)
{
found = true;
position1 = index;
}
index ++;
counter1++;
}
return counter1;
}
解决方案
编译器是对的。你从来没有真正使用过position1
. 让我们看看您访问的所有地方position1
:
//Function for linear search
//int linearSearch(const int arr[], int size, int value)
//{
// int index = 0;
int position1 = -1;
// bool found = false;
// int counter1 = 0;
//
// while( index < size && !found)
// {
// if(arr[index] == value)
// {
// found = true;
position1 = index;
// }
// index ++;
// counter1++;
// }
// return counter1;
//}
您初始化 的值position1
,然后为其分配一个可能有意义的值,计算方式为position1 = index;
现在告诉我:你在哪里读到 的值position1
?
在函数中没有任何地方实际读取 的值position1
,也没有返回它的值。事实上,它的值可能是100000000
or -2
,你的程序将表现相同,因为你从未读取过该值。事实上,您可以完全删除该变量,您的程序仍将表现完全相同!
编译器知道因为position1
是一个局部变量。变量的范围position1
仅在函数内。
推荐阅读
- spring - Spring beans 文件的可配置延迟加载 @Lazy(TRUE/FALSE - 这来自属性文件/系统道具)
- html - 当我关闭并重新打开信息窗口时,如何确保内容保持不变
- laravel-5 - 如何使用 Laravel 在内容中发送邮件动态参数电子邮件?
- laravel - Vuejs动态导入组件导致未加载引导程序
- c++ - 将此类的智能指针附加到成员 std::vector
- datetime - 如何在字符串列上强制 Quicksight 中的 DateTime 字段?
- python-3.x - 按月计数的数据框组
- asp.net-core - Asp.net core uiculture 多线程
- django - 如何区分从 HTML 表单提交的 HTTP 请求和从 django 中的客户端提交的 HTTP 请求?
- mysql - 如何使用 laravel eloquent 连接多个表?