好吧,我从来没有上过 C 编程类(class),我对什么是数组有一个大概的了解,但我似乎无法弄清楚为什么这个数组有特定的输出。
#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
因为您将 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
。这不会导致那样。
我是一名优秀的程序员,十分优秀!