此代码的要点是让用户输入要输入的浮标数量。然后,他们输入所有浮点并对浮点进行排序。最后,它打印结果。问题是,输入浮点值后,我总是遇到分段错误。我已经在代码上有了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);
}
答案 0 :(得分:0)
此代码:
int quantity;
float *data;
{
getData(data, quantity);
将未初始化 data
和quantity
传递到getData
例程中,该例程继续尝试写入*data
(这是一个单独的错误) -应该只是data
)。
难怪程序崩溃。
第一步,为编译器打开最大级警告(如果使用GCC,则使用-Wall -Wextra
),并修复 all 警告。