【发布时间】:2016-04-24 22:57:13
【问题描述】:
#include stdio.h
#include <stdlib.h>
#include <ctype.h>
#define CAPACITY_INCREMENT 6
double average(double data[], int count)
{
double sum = 0.0;
int i;
for(i=0;i<count;sum+=data[i++]);
return sum/count;
}
int main(void)
{
double *data = NULL;
double *temp = NULL;
int count = 0;
int capacity = 0;
char answer = 'n';
do
{
if(count == capacity)
{
capacity += CAPACITY_INCREMENT;
if(!(temp = (double*)realloc(data, capacity*sizeof(double))))
{
printf("Error allocating memory for data values.\n");
exit(1);
}
data = temp;
}
printf("Enter a data value: ");
scanf(" %lf", data + count++);
printf("Do you want to enter another (y or n)? ");
scanf(" %c", &answer, sizeof(answer));
} while(tolower(answer) != 'n');
printf("\nThe average of the values you entered is %10.2lf\n", average(data, count));
free(data);
return 0;
}
我是 C 的初学者,我的一位朋友帮我发了这段代码,我知道这是打印给定数字的平均值,但我不知道某些语法的作用:
if(!(temp = (double*)realloc(data, capacity*sizeof(double))))"
您能逐步解释这是如何工作的吗?
【问题讨论】:
-
scanf(" %lf", data + count++);???这是什么?你能再困惑点吗? -
我投票决定将此问题作为离题结束,因为 SO 不是“解释我的代码”网站。
-
你为什么不简单地给你的朋友打电话/发邮件问问?
-
因为他不知道怎么解释。很抱歉给您带来不便,我只是需要一些帮助。这不是我的代码。不管怎样,谢谢你。 :)
标签: c if-statement syntax realloc