首页 > 解决方案 > C 编程中变量过多导致的错误

问题描述

我想做正数和负数的算术平均值,用户给出数字。我想再放 2 个变量来计算在正面和负面方面相加了多少个数字,然后做算术平均值。

但是当我把它们放进去时int x=0, q=0;,程序停止工作,编译器没有任何错误。为什么?

我得到的错误

int total, i, numere[total], negativeSum = 0, positiveSum = 0;

printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);

for(i=0; i<total; i++){
    printf("Enter number %d : ",(i+1));
    scanf("%d",&numere[i]);
}

for(i=0; i<total ; i++){
   if(numere[i] < 0){
     negativeSum += numere[i];
            }else{
     positiveSum += numere[i];
   }
}

标签: cvariables

解决方案


在你的陈述序列中

int total, i, numere[total], negativeSum = 0, positiveSum = 0;

printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);

total仍然未初始化,因此numere[total]未定义。编译器可能会完全删除它。为了total初始化为定义numere,您必须在阅读后声明它total

int total, i, negativeSum = 0, positiveSum = 0;

printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);

int numere[total]; // now it is well-defined.

推荐阅读