【问题标题】:Receiving non-zero exit status when filling an array dynamically from user input从用户输入动态填充数组时接收非零退出状态
【发布时间】:2017-09-30 19:52:30
【问题描述】:
#include <stdio.h>


  int main(void){

    int inputNumber;
    int counter=0;
    int totalValue;
    int arr[counter];
    int avg;

    puts("Please enter any number of positive whole numbers you would like to be averaged. Enter ' -1 ' when you are finished for your result.\n");

    while(scanf("%d\n", &arr[counter])){

      if(arr[counter] = -1){

        break;
      }
      if(arr[counter] > 0){

        totalValue += arr[counter];
        ++counter;

      }
      else if(arr[counter]<=0){

        puts("Please enter a positive number.");

      }
      else{

      }

    } 

    avg = totalValue/counter;
    printf("The average of your entered values is: %d", avg);
    return 0;
  }

我尝试了很多方法来阻止它,尽管这可能是由于缺乏知识,除了创建一个非常大的数组之外,真的有其他方法吗?

我尝试使用带有 calloc() 的动态数组,但遇到了同样的错误。我不确定在这种方法中还有什么可用的选项。

代码应该取“n”个用户输入值的平均值。

【问题讨论】:

  • malloccalloc 之后使用realloc
  • 如果你只是想求任意数量的整数的算术平均值,没有必要存储所有的值。您只需要跟踪条目的总和和数量。
  • 但是如果你这样做,你最好不要分配一个长度为0的数组。

标签: c arrays exit-code


【解决方案1】:

您不需要数组。

快速而肮脏但你想做的更容易

    int     number = 0;
    int     counter = 0;    
    int     total = 0;

    while (number != -1)
    {
        total += number;
        ++counter;
        scanf("%d", &number);
    }

    printf("average = %d\n", total / (counter - 1) );

【讨论】:

  • 只是那个 avg 应该是 float 而不是 int
  • @ArtemyVysotsky 是的,输入也可以是浮点值,我想这取决于作者想要什么:)
猜你喜欢
  • 2019-07-22
  • 2019-08-06
  • 1970-01-01
  • 1970-01-01
  • 2019-10-08
  • 2017-05-18
  • 2013-12-23
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多