1

提前阅读之前的快速免责声明,这是一个关于我的作业的问题,其中一些要求会非常具体

我正在编写一个代码,该代码从用户那里获取值的数量,这将是数组长度。然后它会要求用户将他们的数字输入到数组中。然后它使用一个函数来确定给定的数组是否连续包含 4 个相同的值。

这是一个示例输出

//example 1
Enter the number of values: 8
Enter the values: 3 4 5 5 5 5 4 5
The list has consecutive fours

//example 2
Enter the number of values: 9
Enter the values: 3 4 5 8 5 5 4 4 5
The list has no  consecutive fours

我的代码的问题是我需要为bool isConsecutiveFour(int values[][4])要完成的问题创建一个函数。我已经尝试过了,因为我最初用于用户输入的数组是一维数组,我认为我不能做到二维。当我将代码全部复制并粘贴到主函数中时,代码可以工作,但是一旦我将其实现到具有要求的函数中,代码就会开始无法按预期工作。在调用函数的地方,我知道有一个预期的表达式,问题是我不确定要放什么,因为原始数组是一维的,而给定函数中的数组是二维的。

#include <iostream>

using namespace std;

bool isConsecultiveFour(int values[][4]);

int main(){

    int x, input;

    cout<<"Enter the number of values: "<< endl;
    cin >> x;

    int arr[x];

    cout<<"Enter the values: "<< endl;
    for(int i = 0; i < x; i++){
        cin>>input;

        arr[i] = input;
    }

    cout<<" "<< endl;

    //error on the second bracket states that it is expecting an expression
    isConsecultiveFour(arr[x][]);


return 0;
}

bool isConsecultiveFour(int values[][4]){

    int count = 1;
   for(int i = 0; i < sizeof(values)/sizeof(values[0]); i++){
       
       if(values[i] == values[i + 1]){
            count++;
       }
   }
   if(count == 4 ){
       cout<<"The list has consecutive fours"<< endl;
   }
   else{
       cout<<"The list has no consecitive fours"<< endl;
   }

   return count;

}
4

1 回答 1

0

您的代码中有多个问题。

  • 关于变长数组和函数中数组大小的主要问题可以使用std::vector.
  • 该函数应返回一个布尔值。
  • 您可以在第四个连续值之后离开循环
  • 如果两个连续值不同,则必须重置计数器。
  • 您不需要用endl.
  • 你应该避免using namespace std;
  • STL 容器或数组的大小类型为std::size_t.
  • 循环结束时差一分。
#include <iostream>
#include <vector>

bool isConsecutiveFour(std::vector<int> values);

int main(){

    std::size_t x;

    std::cout<<"Enter the number of values: \n";
    std::cin >> x;

    std::vector<int> arr(x);

    std::cout<<"Enter the values: \n";
    for(auto &el : arr){
        std::cin>>el;
    }

    std::cout<<" \n";

    isConsecutiveFour(arr);

    return 0;
}

bool isConsecutiveFour(std::vector<int> values){

   int count = 1;
   for(std::size_t i = 0; i + 1 < values.size(); i++){
       
       if(values[i] == values[i + 1]){
           count++;
       } else {
           count = 1;
       }
       if(count == 4 ){
           std::cout<<"The list has consecutive fours\n";
           return true;
       }
   }
   std::cout<<"The list has no consecitive fours\n";
   return false;
}
于 2021-04-07T09:35:39.717 回答