首页 > 解决方案 > 如何正确声明变量

问题描述

我应该编写一个包含 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;
}

标签: c++

解决方案


编译器是对的。你从来没有真正使用过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,也没有返回它的值。事实上,它的值可能是100000000or -2,你的程序将表现相同,因为你从未读取过该值。事实上,您可以完全删除该变量,您的程序仍将表现完全相同!

编译器知道因为position1是一个局部变量。变量的范围position1仅在函数内。


推荐阅读