c - 在 C 中使用 int 值初始化 double 组

标签 c arrays

我现在正在学习一些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 for 4-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/

相关文章:

c - MPIR 编码错误

arrays - $0 和 $1 在 Swift 闭包中是什么意思?

java - 在Java中根据种子创建一个随机整数数组

c - 使用gets读取二维字符串

c - 在 C 代码库中查找全局/静态变量的工具

c++ - 试图理解数组名称的含义

java - DrawerLayout 上的 onClick 监听器不会启动 Toast

c - 我是否正确理解 C 中的按值传递和按引用传递?

c - 如何在 LLVM C API 中使用 LLVMBuildGEP 函数

c - MPI_MAXLOC 用于双值数组