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;
}
代码中没有错误。
在“CentralT......working”之后,我收到以下提示信息: Process returned -1073741571 (0xC00000FD) execution time : 47.686 s Press any key to continue。
解决方案
在 C 中,您无法调整数组的大小。
这条线
int n;
定义n
并将其值保留为垃圾,一个随机值,也许0
.
基于曾经n
持有这条线的东西
int a[n];
定义a
为数组以具有n
现在的元素数量。
读入n
这一行
scanf("%d",&n);
不会改变's 元素的数字。a
要解决此问题,请a
仅在n
具有明确定义的有效值之后定义:
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);
推荐阅读
- python - 根据其他列突出显示 pandas 数据框中的特定列
- python - 用另一列中的值替换特定单词
- input - 如何使 AEM/CRX 中的输入字段成为必需?
- git - 为什么我们第一次使用 git remote add origin?
- javascript - React 添加延迟以在状态中应用类
- android - 无法转换工件 com.twilio:video-android
- arrays - 如何在打字稿的对象数组中找到具有相同属性值的对象?
- python - C++ - 如何将大数组作为函数的输入
- reactjs - 访问 React 组件中的 HTML 元素
- java - 将字符串列表转换为包含这些字符串作为字段的对象列表