数组函数.希望你能澄清一下

Array Function. Would appreciate a little clarification

本文关键字:一下 函数 希望 数组      更新时间:2023-10-16

我有一个关于学校实验室作业的问题,我希望有人能帮我澄清一下。我不是在寻求答案,只是一种方法。我一直不能完全理解书中的解释。

问题:在程序中,编写一个接受三个参数的函数:数组、数组的大小和数字n。假设数组包含整数。函数应该显示数组中所有大于n的数

这是我现在的记录:

/*
Programmer: Reilly Parker
Program Name: Lab14_LargerThanN.cpp
Date: 10/28/2016
Description: Displays values of a static array that are greater than a user inputted value.
Version: 1.0
*/
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
void arrayFunction(int[], int, int); // Prototype for arrayFunction. int[] = array, int = size, int = n
int main()
{  
    int n; // Initialize user inputted value "n"
    cout << "Enter Value:" << endl;
    cin >> n;
    const int size = 20; // Constant array size of 20 integers.
    int arrayNumbers[size] = {5,6,7,8,9,10,11,12,13,14,15,16,17,18,19,20,21,22,23,24}; // 20 assigned values for the array
    arrayFunction(arrayNumbers, size, n); // Call function
    return 0;
}    
/*  Description of code below:
The For statement scans each variable, if the array values are greater than the 
variable "n" inputted by the user the output is only those values greater than "n."
*/
void arrayFunction(int arrayN[], int arrayS, int number) // Function Definiton
{
    for (int i=0; i<arrayS; i++) 
    {    
        if (arrayN[i] > number)
        {
        cout << arrayN[i] << " ";
        cout << endl;
        }
    }    
}

对于我的全部答案,我认为是这样的:

问题:在程序中,编写一个接受三个参数的函数:数组、数组的大小和数字n。假设数组包含整数。该函数应该显示数组中大于n的所有数字。

是整个赋值。

  1. void arrayFunction(int[], int, int);可能是你唯一能写的东西。但请注意,int[]实际上是int*

  2. 正如其他人指出的那样,不要费心接收输入。使用这条线上的东西:int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};。它会为你创建静态数组;

  3. 您有int n参数,但是您从未使用过它。

  4. 您正试图将variable发送到函数arrayFunction,但我看不到此变量的定义!

  5. 使用一些叫做橡皮鸭调试(谷歌查找:))的东西。

如果你有更确切的问题,问他们。

作为一个边注:有更好的方法发送一个数组给函数,但你的赋值强迫你使用这个旧的和不太好的解决方案。

你会使用if else语句吗?我已经用更新后的代码编辑了我的原始帖子。

你更新了问题,我也更新了答案。

首先,正确缩进你的代码!!
如果你这样做了,你的代码将会更干净,更易读,而且不仅对我们来说更容易理解,而且主要对你来说更容易理解。

下一件事:即使在某些上下文中不需要,也不要省略大括号。即使是有经验的程序员也很少会忽略它们,所以作为初学者,你不应该这样做(比如你的for循环)。

关于if-else语句,简短的回答是:视情况而定。
有时我会使用if(注意:在你的情况下else是无用的)。但有时我会使用三元运算符:condition ? value_if_true : value_if_false;甚至lambda表达式。
在这种情况下,您可能应该满足于if,因为它对您来说更容易和更直观。

除了c++方面,考虑一下您需要执行哪些步骤来确定一个数字是否大于某个值。然后对数组中的所有数字执行此操作,并打印出大于n的数字。因为你有一个'for'循环,看起来你已经知道如何在c++中执行循环和比较数字。

另外,它看起来像在你的arrayFunction你试图输入值?

你不能在一个单独的语句中输入整个数组的值,就像你似乎在尝试(此外,'values'不是arrayFunction中任何变量的名称,所以当你试图编译它时,它不会被识别)。