C编程中变量过多导致的错误
我想做正数和负数的算术平均值,用户给出数字。我想再放两个变量,计算正负两个方向的数字之和,然后进行算术平均 但是当我把它们放在int x=0,q=0;程序停止工作,编译器没有任何错误。为什么?C编程中变量过多导致的错误,c,variables,C,Variables,我想做正数和负数的算术平均值,用户给出数字。我想再放两个变量,计算正负两个方向的数字之和,然后进行算术平均 但是当我把它们放在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: : ");
在你的陈述顺序中
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]未定义。编译器可能会将其全部删除。为了使totalinitialized定义numere,您必须在读取total后声明它:
在使用语句numere[total]分配内存之前,需要知道total的值 当您向用户输入total的值时,另一种方法可以是使用malloc
int total, i, *numere, negativeSum = 0, positiveSum = 0;
printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);
numere = malloc(sizeof(int) * 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];
}
}
编译器在运行程序时从不给出运行时错误。这里的数值[total]的总值是多少?首先扫描总值,然后像整数[total];一样声明;。如果它支持VLA,也可以这样做。
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.
int total, i, *numere, negativeSum = 0, positiveSum = 0;
printf("The number of digits you want to calculate the arithmetic amount: : ");
scanf("%d",&total);
numere = malloc(sizeof(int) * 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];
}
}