因此,这里的问题是编写一个程序,该程序使用指针指向函数并以一种方式来收集10次双打,向程序的用户提供反馈,并分类他们并将排序结果打印为证明。问题是,该程序要么无限地打印printf语句,要么无限地收集数字。
这是一些代码
#include <stdio.h>
void func1(double x);
void below_five(void);
void above_five(void);
void other(void);
void sort(double *p[], int n);
void print_doubles(double *p[], int n);
int main(void){
double *numbers[9];
int nbr;
printf("nEnter 10 doubles that are less than 5 or greater than 5, type 0 to exit");
for(int i = 0; i < 10 ; i++)
{
scanf("%d", &nbr);
func1(nbr);
numbers[i] = nbr;
if(nbr == 0)
break;
}
sort(numbers, 10);
print_doubles(numbers, 10);
return 0;
}
void func1(double val)
{
double (*ptr)(void);
if(val <= 5.00){
ptr = below_five;
}else if((val > 5.00) && (val <= 10.00)){
ptr = above_five;
}else
ptr = other;
}
void below_five(void){
puts("You entered a number below or equal to five");
}
void above_five(void){
puts("You entered a number above five");
}
void other(void){
puts("You entered a number well above five.");
}
void sort(double *p[], int n)
{
double *tmp;
for(int i = 0; i < n; i++)
{
if(p[i] > p[i+1]){
tmp = p[i];
p[i] = p[i+1];
p[i + 1] = tmp;
}
}
}
void print_doubles(double *p[], int n)
{
int count;
for(count = 0; count < n; count++)
printf("%dn", p[count]);
}
就像我说的那样,我希望它能够做到的就是将双打收集到SCANF方法中,然后在对数字进行排序后打印数字,但是在这种情况下,似乎For Loop可以永远收集双打。>
我到底做错了什么?
在您的更新代码中查看我的评论。还有其他修改,但是工作代码所需的最小更新下方
#include <stdio.h>
void func1(double x);
void below_five(void);
void above_five(void);
void other(void);
void sort(double p[], int n); /* Simply use a array notation,
arrays passed to functions decays to pointer */
void print_doubles(double p[], int n); /* Simply use a array notation,
arrays passed to functions decays to pointer */
int main(void){
double numbers[10];
double nbr; // Change type to double, as you're reading doubles
printf("nEnter 10 doubles that are less than
5 or greater than 5, type 0 to exitn");
for(int i = 0; i < 10 ; i++)
{
scanf("%lf", &nbr); // Use correct format specifier to read doubles
func1(nbr);
numbers[i] = nbr;
if(nbr == 0)
break;
}
sort(numbers, 10);
print_doubles(numbers, 10);
return 0;
}
void func1(double val)
{
double (*ptr)(void);
if(val <= 5.00){
ptr = below_five;
}else if((val > 5.00) && (val <= 10.00)){
ptr = above_five;
}else
ptr = other;
/* Why you set the pointer to function if you don't call it,
so call it here*/
(*ptr)();
}
void below_five(void){
puts("You entered a number below or equal to five");
}
void above_five(void){
puts("You entered a number above five");
}
void other(void){
puts("You entered a number well above five.");
}
void sort(double p[], int n) /* Your sorting routine is wrong ,
see the modified code */
{
double tmp;
for(int j = 0; j < n-1; j++)
for(int i = 0; i < n-j-1; i++)
{
if(p[i] > p[i+1]){
tmp = p[i];
p[i] = p[i+1];
p[i + 1] = tmp;
}
}
}
void print_doubles(double p[], int n)
{
int count;
for(count = 0; count < n; count++)
printf("%lfn", p[count]); // Use correct format specifier
}
演示此处