我有点被我正在做的一些代码困住了。我要做的是在评论中。
//Write a function that computes the average value of an array of floating-point data:
//double average(double* a, int size)
//In the function, use a pointer variable, not an integer index, to traverse the array
//elements.
#include <iostream>
using namespace std;
double average(double* a, int size)
{
double total = 0;
double* p = a;
// p starts at the beginning of the array
for (int i = 0; i < size; i++)
{
total = total + *p;
// Add the value to which p points
p++;
// Advance p to the next array element
}
return total / size;
}
从它没有运行开始。第二,我真的要正确地解决这个问题吗?基本上我试着按照这本书来遍历所有元素,然后将其平均化……但我有一种强烈的感觉,我遗漏了一些东西。
抱歉,如果这对你们中的一些人来说似乎很明显。我对这一切还很陌生,我的老师也不完全……好吧,她没有教我们 C++ 的编码方面。她所做的只是从 200 多张幻灯片中读取 5 张并进行手动跟踪(甚至不是伪代码),然后通过随机选择我们的编码作业将我们扔进狼群。她的教学方式基本上就好像我们已经知道如何编码,我们中的一些人会这样做,而我们中的一些人(比如我)是第一次看到这一点。
她甚至没有教我们如何使用编译器,所以我们基本上都是自己学习所有这些。 arg,对不起,我继续在那里咆哮。无论如何有人可以帮忙吗?
最佳答案
你的函数是正确的。
Here it is, running, and resulting in the correct output .
如果问题是您没有意识到(尽管这似乎不太可能),我必须添加一个 main
函数并为该函数提供数据:
int main()
{
double array[5] = {1,2,3,4,5};
std::cout << average(array, 5);
}
但这就是我必须做的全部。
关于C++:某些代码出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23056995/