我现在正在学习一些c,并且必须为大学做一个练习。我需要一个 double 组,它应该用 int 值填充。所以我有这个。
#include <stdio.h>
#include <stdlib.h>
int main( int argc, char *argv[] ) {
int size=0, i=0;
printf("Enter size of array: ");
scanf("%d", &size);
double* field = malloc(size * sizeof(double));
double value;
for(i=0; i<size; i++) {
field[i] = i;;
}
for(i=0; i<size; i++) {
printf("Field%i: %d\n",i, field[i]);
}
free(field);
return 0;
}
但是,当我执行它时,所有值都设置为 0。
Enter size of array: 10
Field0: 0
Field1: 0
Field2: 0
Field3: 0
Field4: 0
Field5: 0
Field6: 0
Field7: 0
Field8: 0
Field9: 0
最佳答案
printf
的 %d
代表十进制整数,而不是 double 。
所以这一行:
printf("Field%i: %d\n",i, field[i]);
应该是:
printf("Field%i: %f\n",i, field[i]);
使用错误的格式说明符是 undefined behavior 你之前有过。
来自standard
<小时/>If any argument is not the correct type for the corresponding conversion specification, the behavior is undefined.
还要检查malloc
的返回值。它让您知道分配是否失败(返回NULL
)。
<子> David C. Rankin 的评论提供了更多见解
The
%d
format specifier was looking for4
-bytes (sizeof int
bytes) in memory ordered based on the endianess of your machine. When you provided an 8-byte (sizeof double
) value comprised of a sign-bit, normalized exponent and mantissa, it had no idea what to do with it.
在 printf
中,我们可以使用 %f
代替 %lf
,这也增加了与预兼容的好处C99 版本,而且更短。 (chux指出了这一点)。
关于c - 在 C 中使用 int 值初始化 double 组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48033115/