1
double calculateAverage(double *a);

int main(){

    double *dArray;
    int n, m;

    cout<<"\nplease enter the size of the array: ";
    cin>>n;
    dArray = new double[n];

    for(m=0; m<n; m++){
        cout<<"\nplease enter the number: ";
        cin>>dArray[m];
    }
    *(dArray+m+1) = NULL; // i add this, so for the address after m+1 to be NULL

    cout<<"\n the average of the array is : "<<calculateAverage(dArray)<<endl;

    system("pause");
    return 0;
}


double calculateAverage(double *a){
    double total = 0;
    int iCounter = 0;
    while(*a!=NULL){   // here is the problem!! why it can't be NULL or 0 or empty? // edit from a to *a
        total = total+*a;
        a++;
        iCounter++;
    }

    return total/(iCounter-1); //here edit, from iCounter to iCounter-1
}

我想知道为什么指针不指向 NULL ?谁能告诉我代码哪里出错了?

谢谢你。

一个错字,在分配循环块的数组中应该是“n”而不是“nn”。

4

4 回答 4

2

您无法保证NULL数组末尾的终止符,实际上 C++ 中没有这样的事情,除非您自己使用特定的哨兵(并且在某些情况下使用char*)。此外,在您的具体情况下,您所做的事情毫无意义。

指针是地址,你所做的只是增加地址,它应该怎么变成NULL?从实际的角度来看,假设您将地址传递a == 0x12345678给函数,当您++a将其增加 时sizeof(double),它不会变为零(除非可能溢出)。

由于它是 C++,只需忘记数组并使用 a std::vector(或者,如果您真的想使用标准数组,请将长度作为参数传递给calculateAverage函数)。

于 2013-10-14T03:25:38.067 回答
0

如我所见,您有很多错误

  1. *(dArray+m+1) = NULL--> 如果你将 0 放在你应该使用的数组的末尾*(dArray+m) = NULL
  2. n您分配了一个双打数组并null写入n+1n+1如果您打算使用,请分配n+1......)
  3. 您使用 double 和 int 之间的比较,(*a!=NULL)这可能是错误的,因为在 double 中可能没有 0 的精确表示

您需要决定正确的方法。我建议将元素的数量传递给方法或使用 STL(向量)。

于 2013-10-14T13:40:23.833 回答
0

指针使用 new 分配的数组的第一个元素的地址进行初始化。递增指针会将其移动到数组中下一个双精度数的地址。NULL 是内存开头的地址,因此在遍历整个内存并环绕之前,您的指针不会等于它。

您需要修改代码,以便迭代基于处理的元素数量,而不是指针引用的地址。

于 2013-10-14T03:27:00.420 回答
0
#include<iostream>
#include<limits>
#include<cmath>

using namespace std;
double calculateAverage(double *a);

int main(){

double *dArray;
int n, m;

cout<<"\nplease enter the size of the array: ";
cin>>n;
dArray = new double[n];

for(m=0; m<n; m++){
    cout<<"\nplease enter the number: ";
    cin>>dArray[m];
}
//*(dArray+m+1) = NULL; // i add this, so for the address after m+1 to be NULL
*(dArray+m+1)=numeric_limits<double>::quiet_NaN( );// Jack gave the idea.

cout<<"\n the average of the array is : "<<calculateAverage(dArray)<<endl;

system("pause");
return 0;
}


double calculateAverage(double *a){
    double total = 0;
    int iCounter = 0;
\\while(*a!=NULL){   // here is the problem!! why it can't be NULL or 0 or empty? // edit from a to *a
    while(!_isnan(*a)){ //Jack's idea.
        total = total+*a;
        a++;
        iCounter++;
    }

    return total/(iCounter-1); //here edit, from iCounter to iCounter-1
}

我尝试根据@Jack 的评论修改代码。其他人也提出了非常有价值的想法。非常感谢大家。

我认为该代码现在被认为是可行的。

于 2013-10-18T04:31:32.857 回答