C语言 如何在c中的数组中使用float

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16647702/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 06:24:26  来源:igfitidea点击:

How to use float in an array in c

carrays

提问by Kishan

i want to use float values inside the array for example,

例如,我想在数组中使用浮点值,

array[4];

array[0] = 3.544
array[1] = 5.544
array[2] = 6.544
array[3] = 6.544

float array[] (is giving me error)

but i dont know how to use help me, i am a c beginner

但我不知道如何使用帮助我,我是交流初学者

回答by MOHAMED

You have to specify the size if you are going to define array float in this way:

如果要以这种方式定义数组浮点数,则必须指定大小:

float array[4];

You can define the array without the size. but it should be in this way:

您可以定义没有大小的数组。但它应该是这样的:

float array[] = {3.544, 5.544, 6.544, 6.544};

see the following topic for more details: How to initialize all members of an array to the same value?

有关更多详细信息,请参阅以下主题:如何将数组的所有成员初始化为相同的值?

回答by Tony The Lion

You can't create an array with no static size.

您不能创建没有静态大小的数组。

You can create an array like this on the stack, which is mostly when you have smaller arrays:

您可以在堆栈上创建这样的数组,这主要是在您拥有较小的数组时:

float myarray[12];

it is created in the scope and destroyed when that scope is left.

它在作用域中创建,并在离开该作用域时销毁。

or you can create large arrays using mallocin C, the are allocated on the heap, these need to be manually destroyed, they live until you do so:

或者您可以malloc在 C 中使用创建大型数组,它们在堆上分配,这些需要手动销毁,它们会一直存在,直到您这样做:

// create array dynamically in C
float* myheaparr = malloc(sizeof(float) * 12);

//do stuff with array


// free memory again.
free(myheaparr);

回答by Chirag Desai

float array[4];

array[0] = 3.544;
array[1] = 5.544;
array[2] = 6.544;
array[3] = 6.544;

This should work buddy.

这应该有效,伙计。

回答by OJW

Or for easily initialising the array:

或者为了轻松初始化数组:

float array[4] = {3.544, 5.544, 6.544, 6.544};

float array[4] = {3.544, 5.544, 6.544, 6.544};

回答by varuntv

Specify number of elements you wanna work with while declaring.

在声明时指定要使用的元素数量。

float array[number of elements];

浮点数组[元素数量];

this will statically allocate memory for specified. Access each elements with index. eg

这将为指定的静态分配内存。使用索引访问每个元素。例如

float array[4] will statically allocate memory for 4 floating point variables. array[0] refers to the first element and so on.

float array[4] 将为 4 个浮点变量静态分配内存。array[0] 指的是第一个元素,依此类推。