我在 Windows 7 上使用 Code::Blocks 编译器。它已经给了我几个问题,但从来没有像这个问题那么奇怪。我做了一个将数字上传到数组的函数。这是代码。
int array_read(float array[], const int max_index)
{
int converted, index=0;
char ch='a';
printf("\nEnter up to %d numbers.\n", max_index);
while((index<=max_index)&&(ch!='$'))
{
label:printf("Enter element[%d] or $ if finished.\n", index);
converted=scanf(" %f", &array[index]);
ch=getchar();
if ((converted!=1)&&(ch!='$'))
{
printf("Illegal character '%c'. Try again.\n", ch);
goto label;
}
else
{
if (ch!='$')
{
printf("%f OK.\n", array[index]);
index++;
}
}
}
index=index-1;
return index;
}
这不是一个很好的函数,但只要我输入“$”或索引达到最终数字,当我执行它时,它所做的就是不停地打印一个随机数。有任何想法吗?干杯!!!
最佳答案
没有发现你的函数有什么问题,我在 Linux 机器上用下面的代码块执行了你的代码并给了我预期的结果......
虽然我同意避免使用 GOTO
/* test.c */
#include<stdio.h>
int array_read(float array[], const int max_index)
{
int converted, index=0;
char ch='a';
printf("\nEnter up to %d numbers.\n", max_index);
while((index<=max_index)&&(ch!='$'))
{
label:printf("Enter element[%d] or $ if finished.\n", index);
converted=scanf(" %f", &array[index]);
ch=getchar();
if ((converted!=1)&&(ch!='$'))
{
printf("Illegal character '%c'. Try again.\n", ch);
goto label;
}
else
{
if (ch!='$')
{
printf("%f OK.\n", array[index]);
index++;
}
}
}
index=index-1;
return index;
}
int main()
{
int i;
float f[100];
i = array_read(f,5);
printf("return value is %d \n",i);
return 0;
}
输出如下
$ gcc test.c # no compilation error
$ # for complete run entering all values till loop is over
$./a.out
Enter up to 5 numbers.
Enter element[0] or $ if finished.
2
2.000000 OK.
Enter element[1] or $ if finished.
0234.5
234.500000 OK.
Enter element[2] or $ if finished.
x23
Illegal character 'x'. Try again.
Enter element[2] or $ if finished.
23.000000 OK.
Enter element[3] or $ if finished.
d
Illegal character 'd'. Try again.
Enter element[3] or $ if finished.
-1
-1.000000 OK.
Enter element[4] or $ if finished.
234
234.000000 OK.
Enter element[5] or $ if finished.
7
7.000000 OK.
return value is 5
$
$ # terminating the loop by entering $
$ ./a.out
Enter up to 5 numbers.
Enter element[0] or $ if finished.
2
2.000000 OK.
Enter element[1] or $ if finished.
p
Illegal character 'p'. Try again.
Enter element[1] or $ if finished.
3
3.000000 OK.
Enter element[2] or $ if finished.
$
return value is 1
关于c - 以下数组读取函数有什么问题?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25125509/