【问题标题】:Reading an array with floating point numbers (C programming language)读取带有浮点数的数组(C 编程语言)
【发布时间】:2013-04-28 02:58:00
【问题描述】:

我正在创建一个函数来读取用户的输入,并将它们放入一个浮点数数组中,预定的固定大小为 25。它还返回用户输入的项目总数。但是,由于某种原因,当我输入 999 时,这段代码不会终止。我知道它是一个 int 并且输入是一个浮点数,但我真的不知道如何解决这个问题(只学习 C五天)。

int readArray(float a[]){
    //accepts inputs and puts items in a predefined array of size 25    
    int index = 0;
    float input;
    printf("Enter 25 or less elements for array (999 to finish):\n");

    scanf("%d", &input);  //accept initial response; priming prompt
    printf("1st Prompt accepted");

    while (input != 999 && index < 25) {
        printf("In while loop");

        a[index] = input;
        index++;
        scanf("%d", &input);
    }
    return (index);

}

【问题讨论】:

  • 哦,刚刚意识到,两个打印: printf("1st Prompt accepted");和 printf("在 while 循环中");只是调试代码。
  • Reading floats into an array 的可能重复项

标签: c arrays floating-point numbers


【解决方案1】:

正确的格式说明符在这里很重要。对于浮动它是%f。所以将你的scanf()更改为

scanf("%f", &input);

【讨论】:

  • 对于反对者,我敢于接受 C 中的 float 数字,使用 %d 格式说明符表示 scanf()。告诉我到底如何使用 %d 表示 floats我会放弃C去阿富汗种罂粟。
  • @NikBougalis 请在input!=999比较之前确认999升级为float,这就是表达式没有问题并且程序运行正常的原因。
猜你喜欢
  • 2021-07-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-10-19
相关资源
最近更新 更多