【发布时间】:2017-10-18 00:40:03
【问题描述】:
我是编程新手,但在数组、指针和函数方面仍有问题。我想知道这有什么问题以及如何解决它。特别是为什么指针不能与函数一起使用。这是我正在尝试编写的程序:编写一个程序,该程序动态创建一个指向数组的指针,该数组大到足以容纳用户定义的测试分数数量。一旦输入了所有分数(在主函数中),该数组应该被传递给一个函数,该函数返回一个 DOUBLE 作为平均分数。在用户输出中,平均分数应采用两位小数的格式。使用指针表示法;不要使用数组表示法。
#include <iostream>
#include <iomanip>
#include <memory>
using namespace std;
double getAverage(int, int);
int main()
{
int size = 0;
cout << "How many scores will you enter? ";
cin >> size;
unique_ptr<int[]> ptr(new int[size]);
cout << endl;
int count = 0;
//gets the test scores
for (count = 0; count < size; count++)
{
cout << "Enter the score for test " << (count + 1) << ": ";
cin >> ptr[count];
cout << endl;
}
//display test scores
cout << "The scores you entered are:";
for (count = 0; count < size; count++)
cout << " " << ptr[count];
cout << endl;
double avg;
avg = getAverage(ptr, size);
cout << setprecision(2) << fixed << showpoint << endl;
cout << "The average is " << avg << endl;
return 0;
}
double getAverage(int *ptr, int size)
{
double average1;
double total = 0;
for (int count = 0; count < size; count++)
{
total = total + *(ptr + count);
}
average1 = total / size;
return average1;
}
【问题讨论】:
-
您的程序中有两个不同的函数,名为
getAverage。一个被声明占用两个ints,但从未实现;这是您尝试从main调用的那个,参数类型错误。另一个采用int*和int- 这个已实现,但从未调用。