英文:
Array reading max as one more than input
问题
警告:我对编程极为陌生。如果这段代码看起来很混乱,那是因为确实如此。
我曾经把这段代码完美地运行起来……直到我的笔记本突然重启,我失去了所有的代码。我不得不重新写,但现在,出于某种原因,当我输入一个数组时,它会多加一个数字。
```c
#include <stdio.h>
int main()
{
int length = 0;
int arr[length];
int i;
do {
printf("请输入一个正整数:\n");
scanf("%d", &length);
if (length <= 0)
printf("长度无效,请重试。\n");
}
while (length <= 0);
printf("请输入%d个数字:\n", length);
do {
for (int i = 0; i <= length; ++i) {
scanf("%d", &arr[i]);
}
}
while (length <= 0);
int min = arr[0];
int max = arr[0];
double sum = arr[0];
for (int i = 1; i <= length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum = sum + arr[i];
}
printf("最小值为:%d\n 最大值为:%d\n 平均值为:%f\n", min, max, sum/length);
return 0;
}
示例:数组长度 = 5,数组 = 1 2 3 4 5
最小值 = 1,最大值 = 6,平均值 = 4
我感到困惑和沮丧。我无法再看这个了。
<details>
<summary>英文:</summary>
**Warning: I am extremely new to coding. If this code looks like a mess, it's because it is.**
I had this code literally working perfectly... until my laptop restarted randomly and I lost all my code. I had to rewrite it and now, for some reason, when I enter an array, it adds one extra number to it.
#include <stdio.h>
int main()
{
int length = 0;
int arr[length];
int i;
do {
printf("please enter a positive nonzero integer: \n");
scanf("%d", &length);
if (length <= 0)
printf("Length is invalid. Try again. \n");
}
while (length <= 0);
printf("please enter %d numbers: \n", length);
do {
for (int i = 0; i <= length; ++i) {
scanf("%d", &arr[i]);
}
}
while (length <= 0);
int min = arr[0];
int max = arr[0];
double sum = arr[0];
for (int i = 1; i <= length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum = sum + arr[i];
}
printf("Minimum is: %d\n Maximum is: %d\n Mean is: %f\n", min, max, sum/length);
return 0;
}
Example: array length = 5, array = 1 2 3 4 5
min= 1, max = 6, mean = 4
I'm so stuck and just defeated. I can't look at this any more.
</details>
# 答案1
**得分**: 2
在C语言中,数组的索引从`0`开始。长度为`5`的数组的索引分别为`0`、`1`、`2`、`3`和`4`。通过检查你的索引是否小于或等于长度,你正在进行越界访问。这会导致未定义的行为。
举例来说,你的`for`循环应该如下所示,将`<=`替换为`<`,并从`0`开始:
```c
for (int i = 0; i < length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum = sum + arr[i];
}
英文:
Arrays in C are indexed starting from 0
. An array with a length of 5
has indexes at 0
, 1
, 2
, 3
, and 4
. By checking that your index is less than or equal to the length, you're indexing out of bounds. This results in undefined behavior.
As an example, your for
loop should be the following, subbing <=
for <
and starting at 0
.
for (int i = 0; i < length; i++) {
if (arr[i] > max) {
max = arr[i];
}
if (arr[i] < min) {
min = arr[i];
}
sum = sum + arr[i];
}
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论