C程序:为什么这个数组有这个输出?

时间:2015-01-31 21:40:33

标签: c arrays

好的,所以我从未参加过C编程课程,而且我对数组是什么有一个大概的了解,但我似乎无法弄清楚为什么这个数组有一定的输出。

#include <stdio.h>
#include <time.h>
#include <stdlib.h>  // include srand function
#pragma warning(disable : 4996) 
#define Size 15
main() {
    int a[Size];
    int i;
    double b1[Size], b2[Size];
    srand( (unsigned)time( NULL ) );  // Use current time as seed
    // apply (start) timestamp 
       for (i = 0; i < Size; i++)
    {
        a[i] = rand() % 100; 
              // initialize the array using random number between 0 and 99
        b1[i] = a[i]/5;
        printf("a[%d] = %d\n", i, a[i]);
        printf("b1[%d] = %f\n", i, b1[i]);
        b2[i] = a[i];
        b2[i] = b2[i]/5;
        printf("b2[%d] = %f\n", i, b2[i]);
    }
    // apply (end) timestamp 
    //compute the time elapsed and display time in seconds
}

对于我的作业,我需要运行此代码并解释为什么b1和b2具有相同或不同的值。我似乎无法绕过这里发生的事情:

       for (i = 0; i < Size; i++)
    {
        a[i] = rand() % 100; 
              // initialize the array using random number between 0 and 99
        b1[i] = a[i]/5;
        printf("a[%d] = %d\n", i, a[i]);
        printf("b1[%d] = %f\n", i, b1[i]);
        b2[i] = a[i];
        b2[i] = b2[i]/5;
        printf("b2[%d] = %f\n", i, b2[i]);
    }

如果有人能解释代码在这里做了什么,我将非常感激。 谢谢!

编辑 - 这是我运行程序后的输出:

a[0] = 8
b1[0] = 1.000000
b2[0] = 1.600000
a[1] = 74
b1[1] = 14.000000
b2[1] = 14.800000
a[2] = 78
b1[2] = 15.000000
b2[2] = 15.600000
a[3] = 64
b1[3] = 12.000000
b2[3] = 12.800000
a[4] = 53
b1[4] = 10.000000
b2[4] = 10.600000
a[5] = 6
b1[5] = 1.000000
b2[5] = 1.200000
a[6] = 71
b1[6] = 14.000000
b2[6] = 14.200000
a[7] = 4
b1[7] = 0.000000
b2[7] = 0.800000
a[8] = 7
b1[8] = 1.000000
b2[8] = 1.400000
a[9] = 57
b1[9] = 11.000000
b2[9] = 11.400000
a[10] = 55
b1[10] = 11.000000
b2[10] = 11.000000
a[11] = 13
b1[11] = 2.000000
b2[11] = 2.600000
a[12] = 55
b1[12] = 11.000000
b2[12] = 11.000000
a[13] = 96
b1[13] = 19.000000
b2[13] = 19.200000
a[14] = 25
b1[14] = 5.000000
b2[14] = 5.000000

1 个答案:

答案 0 :(得分:3)

因为您隐式地将int转换为double,并且两次都采用不同的方式。

b1[i] =   a[i]   / 5   ;
/*     ^  ^ int    ^ 
 *     |           +-- int
 *     +-- implicit convertion to double */

b2[i] =  b2[i]     /  5   ;
/*        ^ double    ^
 *                    + int implicitly converted
 *                      to double */
  • 在第一个表达式中,您将int除以int,其中您将失去精确度(即7/2给出3而不是3.5),
  • 在第二个表达式中,您将double除以double。这不会导致这种情况。