在这个程序中,我不太明白注释下面发生了什么:/*pass the array */。该程序的输出应该是输入温度 #0,#1,#2.....#30 的 31 次迭代,然后将这些用户输入的值转换为摄氏度。我的困惑在于函数调用 Convert(temps) 的目的或如何工作以及该函数下面的所有内容如何作为一个整体运行。
任何有关代码如何“工作”以实现所述输出的澄清都会很棒。此外,通过引用发生在转换函数中的调用,如果是的话,有人可以解释一下其中的动态吗?
谢谢。
#define COUNT 31
void convert (float heat[]);
void main()
{
float temps[COUNT];
int index;
/*load the array with values*/
for (index = 0; index < COUNT ; index++)
{
printf("Enter temperature #%d: ", index);
scanf("%f", &temps[index]);
}
/*pass the array */
convert(temps);
for (index = 0; index < COUNT ; index++)
printf("%6.2f\n", temps[index]);
}
/*******************convert function ************************/
void convert (float heat[])
{
int index;
for (index = 0; index < COUNT; index++)
{
heat[index] = (5.0/9.0)*(heat[index]-32);
}
}
最佳答案
函数convert接收指向temps数组第一个元素的指针,然后修改其元素。换句话说,数组永远不会被复制。由于只传递了一个指针,因此无法知道形式参数 heat 在 convert 中存在多长时间。因此,最好也传递数组的长度。我将这样做:
#include <stdio.h>
#include <stdlib.h>
#define LEN(arr) ((int) (sizeof (arr) / sizeof (arr)[0]))
void convert(float heat[], int heatLen)
{
int i;
for (i = 0; i < heatLen; i++) {
heat[i] = (5.0 / 9.0) * (heat[i] - 32);
}
}
int main(void)
{
float temps[31];
int i, nRead;
for (i = 0; i < LEN(temps) ; i++) {
printf("Enter temperature #%d: ", i);
nRead = scanf("%f", &temps[i]);
if (nRead != 1) {
fprintf(stderr, "Invalid input\n");
exit(EXIT_FAILURE);
}
}
convert(temps, LEN(temps));
for (i = 0; i < LEN(temps) ; i++) {
printf("%6.2f\n", temps[i]);
}
return 0;
}
关于C编码: For loop/call by reference confusion,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40882522/