c语言 - 错误:CentralTendencies.exe 在代码块中单击"构建和运行"时已停止工作



此代码用于查找给定数字序列的平均值,中位数和众数。

#include <stdio.h>
#include <math.h>
int main()
{   /*Inputs*/
int n;
int a[n];
/*Outputs*/
float mean;
int median;
int mode;
printf("Enter the size of array: ");
scanf("%d",&n);
for(int i=0; i<n; i++)
{
printf("nEnter the values of array: ");
scanf("%d",&a[i]);
}
/*arrange in ascending order */
int i=0;
for(i=0; i<n-1; i++)
{for(i=0; i<n-1; i++)
{
if(a[i]>a[i+1])
{
int temp = a[i+1];
a[i+1] = a[i];
a[i] = temp;
}
}
}
/*Mean of the series*/
for(i=0; i<n; i++)
{
int sum = 0;
sum = sum + a[i];
mean = sum/n;
}
/*Median of the series*/

我希望这里的类型转换语法是正确的,对吧?

int m = floor((double)n/2);
if(n%2==0)
{
median = (a[m]+a[m-1])/2;
}
else
{
median = a[m];
}
/*Mode of the series*/
int count;
int b = 0;
for(i=0; i<n-1; i++)
{
for(int t=0; t<n; t++)  //Compare a[i] with all the elements of the array
{if(a[i]==a[t])
{
count = 0;
count++;
}
if(b<count)                //Update the new value of mode iff the frequency of one element is greater than that
{                   // of its preceding element.
mode = a[i];
}
}
}
printf("The value of mean: %f",mean);
printf("nThe value of mean: %d",median);
printf("nThe value of mean: %d",mode);
return 0;
}

代码中没有错误。

我在"中央T...工作": 进程返回 -1073741571 (0xC00000FD( 执行时间 : 47.686 s 按任意键继续。

在 C 中,您不能调整数组的大小。

此行

int n;

定义n并将其值保留为垃圾,一个随机值,也许是0

基于n持有这条线的内容

int a[n];

a定义为数组,以具有现在n的元素数。

阅读这一行中的n

scanf("%d",&n);

不会更改a元素上的数字。

若要解决此问题,请仅在n具有明确定义的有效值后定义a

scanf("%d",&n);
int a[n];

要真正确保已设置n,您需要测试scanf()的结果,例如:

do {
if (1 != scanf("%d, &n))
{
puts("Bad input or failure reading n!n");
continue;
}
} while (0);

相关内容

最新更新