【发布时间】:2021-05-04 21:51:51
【问题描述】:
我对编程还是很陌生,在 C 之前我唯一的经验是 Javascript。我正在做 CS50 Introduction to Computer Science 并且在其中一堂课中有一个示例代码可以计算一些用户输入的平均值。它看起来像这样:
#include <cs50.h>
#include <stdio.h>
const int TOTAL = 3;
float average(int length, int array[])
int main(void)
{
int scores[TOTAL];
for (int i = 0; i < TOTAL; i++)
{
scores[i] = get_int("Score: ");
}
printf("Average: %f\n", average(TOTAL, scores);
}
float average(int length, int array[])
{
int sum = 0;
for (int i = 0; i < length; i++)
{
sum += array[i];
}
return sum / (float) length;
}
我要添加的功能是根据用户输入动态存储数组的大小,而不是只有一个变量(在本例中为 TOTAL)。例如:我需要有一个循环,它总是向用户询问分数(而不是像上面的代码那样只有 3 次),当用户键入零(0)时,循环中断并且数组的大小是由用户输入分数的次数来定义。
这就是我所做的:
int main(void)
{
int score;
// start count for size of array
int count = - 1;
do
{
score = get_int("Score: ");
// add one to the count for each score
count++;
}
while (score != 0);
// now the size of the array is defined by how many times the user has typed.
int scores[count];
for (int i = 0; i < count; i++)
{
// how do I add each score to the array???
}
}
我的问题是如何将用户键入的每个分数添加到数组中。提前谢谢!!!
【问题讨论】:
-
关于:
float average(int length, int array[]) int main(void)第一条语句后缺少分号;,因此无法编译 -
关于:
printf("Average: %f\n", average(TOTAL, scores);这在半色;之前缺少一个右括号,因此无法编译! -
关于:
return sum / (float) length;这会导致编译器输出警告消息:untitled1.c:30:16: 警告:从 'int' 到 'float' 的转换可能会改变值 [- Wconversion] 编译时,始终启用警告,然后修复这些警告。 (对于gcc,至少使用选项:-Wall -Wextra -Wconversion -pedantic -std=gnu11)注意:其他编译器使用不同的选项来产生相同的结果 -
注意,只计算平均值,只需要保留输入值的总和和输入值的个数;您不需要具有已保存值的数组。然后,您可以简单地读取数字直到 EOF(或输入错误,例如字母或标点字符),然后通过计算
(double)sum / count打印平均值。