此代码的要点是让用户输入他们想要输入的浮点数的数量。然后,他们进入所有浮标并对浮标进行排序。最后,它打印结果。问题是,在输入浮点值后,我不断遇到分段错误。我已经在代码上有了库stdio.h和string.h。它们只是没有显示在这里。谢谢!
int quantity();
void getData(float *dataStart, int quantity);
void sortData(float *dataStart, int quantity);
void printData(float *dataStart, int quantity );
float sumData(float *dataStart, int quantity);
void total(float total);
int main()
{
int quantity;
float *data;
{
getData(data, quantity);
sortData(data, quantity);
printData(data, quantity);
printTotal(sumData(data, quantity));
free(data);
}
return 0;
}
int quantity()
{
int choice;
do
{
printf("nHow many data values are there (2 to 200, 0=quit): ");
scanf ("%d", &choice);
}
while((choice < 2 || choice > 200) && choice != 0);
return choice;
}
void getData(float *dataStart, int quantity)
{
float *data;
for(data = dataStart; (data - dataStart) < quantity; data++)
{
printf("Enter data value %f: ", *data);
scanf("%f", data);
}
return;
}
void sortData(float *dataStart, int quantity)
{
float *data,
*sort,
*sortStart,
*biggest;
for(sort = sortStart; (sort - sortStart) < quantity; sort++)
{
*sort = 0.0f;
for(data = dataStart; (data - dataStart) < quantity; data++)
{
if(*data >= *sort)
{
*biggest = *data;
*sort = *biggest;
}
*biggest = 0.0f;
}
}
memcpy(data, sort, sortStart);
free(sort);
return;
}
void printData(float dataStart, int quantity)
{
float data;
for(data = dataStart; (data - dataStart) < quantity; data++)
{
printf(" %.2f", *data);
}
return;
}
float sumData(float *dataStart, int quantity)
{
float *data,
dataTotal = 0;
for(data = dataStart; (data - dataStart) < quantity; pdata++)
dataTotal += *data;
return dataTotal;
}
void print total(float total)
{
printf("The total is : %.2f", total);
}
此代码:
int quantity;
float *data;
{
getData(data, quantity);
将未初始化的data
和quantity
传递到getData
例程中,该例程继续尝试写入*data
(这是一个单独的错误 - 它应该只是data
(。
难怪程序崩溃。
第一步,为编译器打开最大警告级别(如果使用 GCC,请使用-Wall -Wextra
(,并修复所有警告。