以下数组读取功能有什么问题?

时间:2014-08-04 18:48:22

标签: c arrays

我在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;
}

这不是一个非常好的功能,但只要我输入'$'或索引达到最终数字,当我执行它时它所做的就是打印一个随机数而不停止。有任何想法吗?干杯!!!

2 个答案:

答案 0 :(得分:1)

看不出你的功能有什么问题,我在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

答案 1 :(得分:0)

当没有ansi C参数规范时,传递给函数的C中的参数被提升为double,因此,printf或scanf的所有参数必须是双精度,尝试将float更改为double并查看它是否正常工作。