【问题标题】:If statement is not accessing the value of an array (using the index) when evaluating the expressionif 语句在评估表达式时未访问数组的值(使用索引)
【发布时间】:2021-06-27 23:23:51
【问题描述】:

我应该创建一个程序,要求用户填充大小为 10 的数组。有三个函数,它们的名字是不言自明的;第一个函数用元素填充数组,第二个函数水平显示数组,第三个函数检查用户输入的数字是否是数组中的元素。

#include<iostream>
#include<iomanip>
void fillUpArray(int array[], int size);
void displayArray(int array[], int size);
bool isNumberPresent(int array[], int size, int SearchNum);
    
int main(){
  int s = 10; //size of array
  int A[s]; //array A with size s
  int num; //search number
      
  fillUpArray(A, s);
    
  std::cout <<"\n";
    
  displayArray(A, s);
    
  std::cout << "\n";
    
  std::cout << "Enter a number to check if it is in the array:\n";
  std::cin >> num;
    
  std::cout << std::boolalpha << isNumberPresent(A, s, num) << std::endl;
    
  return 0;
      
}
    
void fillUpArray(int array[], int size)
{
  std::cout << "Enter 10 integers to fill up an array, press enter after every number:\n";
  for(int i = 0; i < size; i++){
        
    std::cin >> array[i];
  
  }
    
}

void displayArray(int array[], int size)
{
  for(int j = 0; j < size; j++){
    std::cout << array[j] << "\t";
  }
}

bool isNumberPresent(int array[], int size, int SearchNum)
{
  bool isPresent;
  for(int k = 0; k < size; k++){
    if(array[k] == SearchNum)
      isPresent = true;
    else
      isPresent = false;
  }
  return isPresent;
}

最后一个函数,它是一个布尔函数,并没有像我想象的那样执行。我认为通过执行array[k] 无论索引k 是什么,它都应该吐出数组中的元素,然后使用表达式if(array[k] == SearchNum) 它应该像if(element == SearchNum) 一样工作,但情况似乎并非如此,输出总是假的。

【问题讨论】:

  • 在调试器中单步执行您的程序,并注意执行流程与您预期的不同之处。
  • @chris 是的,对不起,我应该声明我不在您的标准 IDE 中编程。我使用replit.com。我正在下载 Visual Studio 的过程中(当我完成输入时),因为如果没有适当的调试器,我无法完成我的 CS 作业需要更多时间。
  • 在这种情况下,有些人喜欢使用的另一种策略是添加打印语句来检查执行流程和值,直到问题缩小到特定的行或其他小代码单元。
  • 一些可能有帮助的问题:如果数组的大小为 0 会发生什么?如果搜索匹配数组中的最后一项怎么办?如果它匹配第一个但不匹配最后一个怎么办?它可以匹配数组中的多个条目吗?
  • @chris 谢谢你的帮助。我确实尝试过做同样的策略,我想我到了某个地方!给您添麻烦了!

标签: c++ arrays function if-statement


【解决方案1】:

isNumberPresent 函数中的for 循环将运行到数组的末尾(直到k 等于size无条件;在该循环的每次运行中,您根据当前元素是否与searchNum 匹配来设置isPresent 变量的值,覆盖之前的值。因此,就目前而言,该函数将简单地返回数组中的 last 元素是否与给定的测试编号相同。

您可以简化该函数并消除对局部变量的需要:如果找到匹配项,则立即返回true;如果循环结束但没有找到匹配项,则返回false

bool isNumberPresent(int array[], int size, int SearchNum)
{
  for(int k = 0; k < size; k++){
    if(array[k] == SearchNum) return true; // Found a match - we can return immediately
  }
  return false; // We didn't find a match
}

另外请注意,可变长度数组 (VLA) 不是标准 C++ 的一部分,尽管一些编译器(如 GNU g++)支持它们(它们根据 C99 的 C 语言的一部分标准)。在您的程序中,由于您只使用一个(固定)值作为数组大小,您可以通过限定 s 是一个 const 来符合标准 C++:

int main()
{
    const int s = 10; //size of array - make this a "const" be 'proper' C++
    int A[s]; //array A with size s
//...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-27
    • 2012-04-29
    • 2011-07-22
    • 1970-01-01
    相关资源
    最近更新 更多