变量不保持其值

时间:2017-11-10 00:14:56

标签: c gcc

在下面的代码片段中,由于某种原因,eror的值不在FOR循环之外。

    eror = 0 ;
    for (i=0; i<n; i++) 
    {
        predict = intercept + (slope * data[i][0]) ;
        printf("In the FOR loop eror =  %lf\n", eror) ;
        eror +=(data[i][1] - predict) ;
    }
    printf("Out of FOR loop eror = %lf\n", eror) ;

部分输出是......

    In the FOR loop eror =  -0.028400
    In the FOR loop eror =  -0.011216
    In the FOR loop eror =  0.012196
    In the FOR loop eror =  0.019527
    In the FOR loop eror =  0.024293
    In the FOR loop eror =  0.021309
    In the FOR loop eror =  0.013337
    Out of FOR loop eror = -0.000000

任何人都可以解释为什么FOR循环中有一个值,但是一旦变量eror退出FOR循环就没有了吗?

1 个答案:

答案 0 :(得分:0)

尝试:

eror = 0 ;
for (i=0; i<n; i++) 
{
    predict = intercept + (slope * data[i][0]) ;
    eror +=(data[i][1] - predict) ;
    printf("In the FOR loop eror =  %lf\n", eror) ;
}
printf("Out of FOR loop eror = %lf\n", eror) ;