数组不能打印正确的值

时间:2017-02-11 23:21:19

标签: c arrays

我正在尝试从文本文件中读取数字并将其存储到数组中。 当我尝试读取数组中的数字时,输出略微偏离。 这是我的代码:

struct point{
    double x[7];
    double y[7];
}point;

int main()
{
    FILE *fp;
    fp = fopen("data_2.txt", "r");
    struct point points;
    int len = 8;
    int i = 0;
    int j = 0;
    int k = 0;
    double a = 0;
    double b = 0;
    double c = 0;
    double total = 0;
    int left=0;
    int right=0;
    int line = 0;
    for (i=0;i<len;i++)
    {
        fscanf(fp, "%lf %lf", &points.x[i],&points.y[i]);
    }
    for(i = 0; i < len;i++)
        printf("looking at point %.2f %.2f\n",points.x[i],points.y[i]);

    return(0);
}

我使用的测试文件包含以下数字

  2.3  7.5
  7.6  7.1
  8.5  3.0
  5.9  0.7
  1.0  2.0 
  5.1  5.8
  4.0  4.5 
  4.3  3.4

我得到的输出是:

looking at point 2.30 4.30
looking at point 7.60 7.10
looking at point 8.50 3.00
looking at point 5.90 0.70
looking at point 1.00 2.00
looking at point 5.10 5.80 
looking at point 4.00 4.50
looking at point 4.30 3.40

我做错了什么?

2 个答案:

答案 0 :(得分:7)

问题是你的struct不够大,无法存储8个数字,而且它正在调用undefined behavior。你有double x[7],但你正在循环到8。

为什么你会得到那种特定的行为,我可以在OS X上重现它,我不确定。但这对你来说是不确定的行为。

答案 1 :(得分:3)

像这样更新你的结构:

<console>:38: error: overloaded method value select with alternatives:
  (col: String,cols: String*)org.apache.spark.sql.DataFrame <and>
  (cols: org.apache.spark.sql.Column*)org.apache.spark.sql.DataFrame
cannot be applied to (String, String, String, String, String, String, String,org.apache.spark.sql.Colum)

...

这将帮助您正确阅读和显示数据。 example-with-stdin