填充整数数组与填充浮点数一样吗? [英] Is populating an integer array the same as populating a float one?

查看:137
本文介绍了填充整数数组与填充浮点数一样吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚刚被介绍给C,我被分配去编写一个程序,该程序模仿杂货店的自助结帐行.这涉及到我必须根据用户输入用杂货项目的价格填充一个数组,然后将它们加起来并将其复制到文件中.

I'm just getting introduced to C, and I was assigned to write a program that would mimic a self check out line at a grocery store. This involves me having to populate an array with the prices of grocery items based on user input, and add them up and copy them to a file.

填充整数数组的最简单方法是使用for循环.但这对于float类型的数组会有所不同吗?

the easiest way to populate an integer array is with a for loop. But would that be different for an array of type float?

看起来像这样吗?还是不正确?

would it look something like this? Or is this incorrect?

int size, i;
float items[size];
printf("How many items are you checking out today?");
scanf("%d", &size);
for(i=0;i<size;i++){
  printf("Enter the price of an item\n");
  scanf("%f", items[i]);
}

我是这个网站的新手,所以在此先感谢

I'm new to this site so thanks in advance

推荐答案

我建议您在声明变量时始终对其进行初始化,以防止偶然的垃圾"值.另外,我不建议您预先声明循环计数器.您可以在许多旧代码中看到它(由于编译器的限制,以前必须使用它),但现在我只是认为这是代码的噪音.看起来像这样:

I would recommend always initializing variables as you declare them to prevent "garbage" values by accident. Also, I don't really recommend pre-declaring your loop counters. You see it in a lot of old code (it used to be required due to compiler limitations), but now I just think it's code noise. It would look like this:

for (int i = 0; i < size; i++) {
    // stuff
}

此外,您的代码有很大的问题.您正在使用所谓的可变大小数组,它们是

Also, your code has a big problem. You're using what's known as a variable-size array, and they are not a good idea. You generally want to either declare the array size at compile time, or dynamically allocate the space for the array using malloc.

不过,回到初始化,这就是在声明时设置堆栈分配的数组中的每个元素的方式:

Going back to the initalization, though, this is how you would set every element in a stack-allocated array on declaration:

#define SIZE 4

int main(void)
{
    float items[SIZE] = { 0 };
}

如果您动态分配数组,出于相同原因,我建议使用callocmemset将数组元素设置为默认值.

If you dynamically allocate the array, I recommend using calloc or memset to set the array elements to a default value for the same reason.

要回答有关填充数组的问题,是的,关于实际执行此操作的方式没有区别. for循环在两种情况下都可以正常工作.只需记住检查scanf的返回值即可.

To answer your question about populating the array, yes, there is no difference as to how you would actually go about doing it. A for loop works just fine in both cases. Just remember to check the return value of scanf.

这篇关于填充整数数组与填充浮点数一样吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆