读取浮点数到数组中 [英] Reading floats into an array

查看:115
本文介绍了读取浮点数到数组中的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我怎么读10个浮点数并将它们存储在一个数组中而又不浪费任何内存?

How could I read let's say 10 floats and store them in an array without wasting any memory?

推荐答案

啊哈.问题不是读取浮点数,而是内存.您读了 i ,并且需要一个完全容纳 i 浮点数的数组.

Aha. It's not reading the floats that's the problem, it's the memory. You read in i, and you need an array that holds exactly i floats.

这确实闻起来像家庭作业,很好,但是我老师太多了,无法给您完整的答案.因此,我告诉您,您需要的是一个名为 malloc()的C函数和一个名为 sizeof .

This really does smell like homework, which is fine, but I'm too much the teacher to give you the full answer. So I'll tell you, what you need is a C function named malloc() and a C operator (it looks like a function but it's actually built into the language) named sizeof.

请参阅本教程.

是的,你到了那里.这是您注释中的代码,格式设置.

Yup, you got it there. Here's the code from your comment, formatted.

int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)calloc(n,sizeof(float));
for(index=0;index<n;index++) {
    scanf("%f",&temp); 
    *(pValues+index)=temp;
}

我要做两个更改:

  1. malloc用于字符之外的其他任何东西
  2. 在C语言中,数组和指针之间的关系非常密切;实际上,*(pValues+index)完全等同于pValues[index].
  1. Its more idiomatic to use malloc for anything besides characters
  2. In C, arrays and pointers have a very close relationship; in fact *(pValues+index) is exactly equivalent to pValues[index].

所以我将其重写为:

int n,index;
float temp;
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
    scanf("%f",&temp); 
    pValues[index]=temp;
}

让我们看一下代码的另一种转换.您有pValues,它是指向float的指针.您有&temp,它也是float的指针,因为&是运算符的地址,而tempfloat. AND,您只是对索引进行指针算术运算.因此,我们可以再重写一次为:

Let's look at one more transformation of the code. You have pValues, which is a pointer to float. You have &temp, which is also a pointer to float, because & is the address-of operator and temp is a float. AND, you're just doing pointer arithmetic with your index. So, we could rewrite this one more time as:

int n,index;    // Don't need temp
scanf("%d",&n);
float *pValues=(float *)malloc(n*sizeof(float));
for(index=0;index<n;index++) {
    scanf("%f",pValues+index); 
}

现在,测验问题:如果执行循环,会发生什么

Now, quiz question: what would happen if you made the loop

for(index=0;index<n;index++) {
    scanf("%f",pValues++); 
}

这篇关于读取浮点数到数组中的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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