数组函数.希望你能澄清一下
Array Function. Would appreciate a little clarification
我有一个关于学校实验室作业的问题,我希望有人能帮我澄清一下。我不是在寻求答案,只是一种方法。我一直不能完全理解书中的解释。
问题:在程序中,编写一个接受三个参数的函数:数组、数组的大小和数字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的所有数字。
是整个赋值。
-
void arrayFunction(int[], int, int);
可能是你唯一能写的东西。但请注意,int[]
实际上是int*
。 -
正如其他人指出的那样,不要费心接收输入。使用这条线上的东西:
int numbers[] = {2,4,8,5,7,45,8,26,5,94,6,5,8};
。它会为你创建静态数组; -
您有
int n
参数,但是您从未使用过它。 -
您正试图将
variable
发送到函数arrayFunction
,但我看不到此变量的定义! -
使用一些叫做橡皮鸭调试(谷歌查找:))的东西。
如果你有更确切的问题,问他们。
作为一个边注:有更好的方法发送一个数组给函数,但你的赋值强迫你使用这个旧的和不太好的解决方案。
你会使用if else语句吗?我已经用更新后的代码编辑了我的原始帖子。
你更新了问题,我也更新了答案。
首先,正确缩进你的代码!!
如果你这样做了,你的代码将会更干净,更易读,而且不仅对我们来说更容易理解,而且主要对你来说更容易理解。
下一件事:即使在某些上下文中不需要,也不要省略大括号。即使是有经验的程序员也很少会忽略它们,所以作为初学者,你不应该这样做(比如你的for
循环)。
关于if-else语句,简短的回答是:视情况而定。
有时我会使用if
(注意:在你的情况下else
是无用的)。但有时我会使用三元运算符:condition ? value_if_true : value_if_false;
甚至lambda表达式。
在这种情况下,您可能应该满足于if
,因为它对您来说更容易和更直观。
除了c++方面,考虑一下您需要执行哪些步骤来确定一个数字是否大于某个值。然后对数组中的所有数字执行此操作,并打印出大于n的数字。因为你有一个'for'循环,看起来你已经知道如何在c++中执行循环和比较数字。
另外,它看起来像在你的arrayFunction你试图输入值?
- "error: no matching function for call to"构造函数错误
- 什么时候调用组成单元对象的析构函数
- 继承函数的重载解析
- 为什么随机数生成器不在void函数中随机化数字,而在main函数中随机化
- 有人可以解释一下这个矩阵幂函数是如何工作的吗?
- 请描述一下在 c++ 中在此类中定义构造函数的方式?
- 有人能解释一下特殊的std::函数模板参数列表语法(这个奇怪的类型(Types..))吗
- 不太清楚为什么我的递归链表删除函数有效?我很想解释一下
- 有人可以解释一下这里发生了什么(类和构造函数/析构函数)吗?
- 你能解释一下这个C++函数定义的语法吗?
- 调用私有函数并且它有效.请你们中的任何人推理一下
- 有人能解释一下这个模板函数声明的语法吗
- c++新手,你能解释一下这个构造函数语法吗?
- 我的函数调用出错了,有人能解释一下原因吗
- 数组函数.希望你能澄清一下
- 你能用英语尽可能简单地解释一下什么是复制构造函数,什么时候需要使用它吗?
- 有人能向我解释一下为什么sizeof函数在下面的代码中返回不同的值
- 有人能解释一下为什么只有一个函数打印到控制台吗?
- 有人能给我解释一下这个函数的最后一个参数吗?
- 有人能解释一下这些函数返回类型的区别吗?