【发布时间】:2019-08-28 22:26:50
【问题描述】:
我正在尝试编写一个代码,该代码将从用户那里获取 20 个整数的输入,并对其进行操作以找到平均值、最大值、最小值和标准差。我在网上找到的所有内容都说按地址传递数组,我认为我做得正确,但可能是我的问题。
输入 20 个数字后,我不断收到“分段错误(核心转储)”,但不知道为什么。我也收到此警告“hw06.c:38: warning: format '%d' expects type 'int', but argument 2 has type 'int **'”,我也不知道如何解决这个问题。
修复这些错误后,我认为我的最大/最小循环和可能的标准偏差不正确。
我尝试了很多不同的东西。我终于摆脱了以前遇到的错误,因为我没有按地址传递数组,但我什至不知道如何解决这个错误。我在下面粘贴了我的整个代码:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define SIZE 20
void getInput(int score[SIZE]);
double getMean(int *score[SIZE]);
void getCalc(int *score[SIZE], double avg);
int main()
{
int score[SIZE] = {0};
double avg;
getInput(score[SIZE]);
avg = getMean(&score[SIZE]);
getCalc(&score[SIZE], avg);
return 0;
}
void getInput(int score[SIZE])
{
int count = 0;
printf("Enter 20 integer values -> ");
for (count = 0; count < SIZE; count++)
{
scanf("%d ", &score[count]);
printf("%d", score[count]);
}
return;
}
double getMean(int* score[])
{
int count = 0;
int totalNum = 0;
double avg;
printf("\nData set as entered: ");
for (count = 0; count < SIZE; count++)
{
totalNum = totalNum + *score[count];
printf("%d, ", *score[count]);
}
avg = ((double)totalNum / 20.0);
printf("\nMean: %.2lf", avg);
return avg;
}
void getCalc(int* score[], double avg)
{
int count = 0;
double deviation;
double standard;
int max;
int min;
for (count = 0; count < SIZE; count++)
{
deviation += (*score[count] - avg);
//printf("%lf", deviation);
if (*score[count] > *score[count - 1])
{
max = *score[count];
}
else
{
min = *score[count];
}
}
standard = (double)deviation / 20.0;
printf("\nMean Deviation: %.2lf ", standard);
printf("\nRange of Values: %d, %d", min, max);
return;
}
代码应该从用户那里获取一个包含 20 个值的数组,然后将其传递给下一个函数,它将打印数字(这次用逗号分隔,最后一个不需要,但我不确定如何摆脱它)。然后它需要找到平均值,该平均值之前工作正常,但从那以后我已经改变了。
接下来,它需要将平均值传递给标准偏差函数,在该函数中计算标准偏差(每个值的总和 - 平均值除以 20)并找到数组的最大值/最小值。
我目前只是收到一个错误。
【问题讨论】:
-
警告(尽管令人惊讶)与您的崩溃密切相关...这个程序有很多错误,您应该请您的教授或老师与您一起检查...
-
需要后退一步,因为您的数组是一个指针数组。
int *score[SIZE] = {0};应该是int score[SIZE] = {0};并且后续的所有后果,例如void getInput(int *score[SIZE])应该是void getInput(int score[])和scanf("%d ", score[count]);应该是scanf("%d ", &score[count]);和printf("%d", &score[count]);应该是printf("%d", score[count]);。以此类推。 -
getInput(&score[SIZE]);肯定是一个错误 - 将数组score之外的地址传递给getInput()。 -
@WeatherVane 这是我以前拥有的,但是当我将其更改为“c:29: error: conflicting types for 'getInput' hw06.c:13: note: previous declaration of 'getInput' 在这里”,另一个班级的学生告诉我,这是因为我们需要通过地址而不是值来传递数组,这就是为什么我尝试添加 * 和 & 符号
-
正如我所写,
int score[SIZE] = {0};和getInput(score);以及我在第一条评论中提到的scanf和printf的更改。
标签: c for-loop max min standard-deviation