gpt4 book ai didi

C 程序 : Why does this array have this output?

转载 作者:太空宇宙 更新时间:2023-11-04 07:11:11 25 4
gpt4 key购买 nike

好吧,我从来没有上过 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。这不会导致那样。

关于C 程序 : Why does this array have this output?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28256829/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com