对象数组值" nan"

时间:2016-12-26 19:55:53

标签: c++

我执行程序时遇到问题,我得到的结果是" nan"对于vector的值。我不确定错误在哪里。方法distancias生成一个正确的值,但方法变量图不生成期望值,而不是生成一个值" nan"。对我的英语来说。

#include <iostream>
#include <math.h>

//this program is to calculate the kriging puntual 
using namespace std;

////
class Points{
    private:
        float x;
        float y;
    public:
        Points(float a,float b);
        Points();
        float distancia(float x_1,float y_1);
        float variogram(float h);
        float valor_1();
        float valor_2();
        void show(void);
};

Points::Points(){

}
Points::Points(float a,float b){
    x=a;
    y=b;
}
float Points::distancia(float x_1,float y_1){
    float d;
    d=pow(pow((x-x_1),2)+pow((y-y_1),2),0.5);
    return d;
}
float Points::variogram(float h){
    float v,c_0,c_1,a_1;
    v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
    return v;
}
void Points::show(void){
    printf("%.2f,%.2f\n",x,y);
} 
float Points::valor_1(){
    return x;
}
float Points::valor_2(){
    return y;
}


///////
int main(int argc, char** argv) {
    float a_1,c_0,c_1;      //parameters of variogram
    float c,d;              // position of point to determinate
    float a,b;              //positions of all points except the point to      determinate
    int i=0,n;
    int j,k;

    Points final;           //point to determinate

    //this part is to enter the values of function sphere variogram

    printf("Enter the paramters of sphere variogram\n");
    printf("Enter the value of c_0: ");
    scanf("%f",&c_0);
    printf("Enter the value of c_1: ");
    scanf("%f",&c_1);
    printf("Enter the value of a: ");
    scanf("%f",&a_1);

    //determinating the postion of final point

    printf("Enter the position of the point to determinate: ");
    scanf("%f,%f",&c,&d);
    final=Points(c,d);
    final.show();


    printf("Enter the name of points for the krigeage: ");
    scanf("%i",&n);
    Points punto[n];
    float vector[n];
    do{
        printf("Enter the position x,y of the point %i: ",i+1);
        scanf("%f,%f",&a,&b);
        punto[i]=Points(a,b);
        punto[i].show();
        vector[i]=punto[i].variogram(punto[i].distancia(c,d));
        cout<<vector[i]<<endl;
        i=i+1;
    }while(i<n);
return 0;
}

1 个答案:

答案 0 :(得分:0)

问题在于以下功能:

float Points::variogram(float h){
    float v,c_0,c_1,a_1;
    v=c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
    return v;
}

在这里,您要声明局部变量vc_0c_1a_1。这些值未初始化,它们可以包含任何内容。但是,它们实际上并不等于零。因此,当您计算h/a_1时,其结果可能是加或减无穷大。当您使用相同符号相减两个无穷大时,结果将为NaN

您应该做的是将c_0c_1a_1的值从main()传递给函数:

float Points::variogram(float h, float c_0, float c_1, float a_1){
    return c_0+c_1*(1.5*(h/a_1)-0.5*pow((h/a_1),3));
}

...

vector[i]=punto[i].variogram(punto[i].distancia(c,d), c_0, c_1, a_1);

请在启用警告的情况下编译代码(如果使用GCC,则使用-Wall命令行选项)。然后,您的编译器应该警告您这些未初始化的变量。