问题描述
我的代码中有一个小问题,无法从一系列数字中找到最小值.当我初始化min = 0
时,最小值变为0.但是当我不初始化min
时,答案是正确的!
I have a small problem in my code for finding the minimum value from a series of numbers. When I initialize min = 0
, the minimum value turns out as 0. But when I don't initialize min
, the answer is correct!
为什么会这样? Xcode告诉我应该初始化min
变量.
Why does this happen? Xcode tells me I should initialize the min
variable.
int a[20] = {0};
int max = 0;
int min ;
int sum = 0;
srand((unsigned)time(NULL));
for (int i = 1; i <= 20; i++) {
a[i] = 100 + rand()%(200 - 100 + 1);
if (max < a[i]) {
max = a[i];
}
printf("%d,%d\n",a[i],i);
if (min > a[i]) {
min = a[i];
}
sum += a[i];
}
printf("最大值:%d\n",max);
printf("最小值:%d\n",min);
printf("平均值:%d\n",sum / 20);
推荐答案
编译器警告是因为访问未初始化变量的值会带来未定义的行为.
The compiler warning is because accessing the value of uninitialised variables gives undefined behaviour.
在数组中查找最小值的常用技术是将min
初始化为数组中的第一个元素,然后遍历后续元素
A common technique to find a minimum value in an array is to initialise the min
to be the first element in the array, then iterate over subsequent elements
min = a[0];
for (i = 1; i < 20; ++i) /* assume 20 elements */
if (a[i] < min) min = a[i];
这适用于可以使用<
运算符进行比较的所有数字类型,而不必费力尝试查找超出数组中所有可能值的值.
This works for all numeric types that can be compared using the <
operator, without having to muck around trying to find a value that exceeds all possible values in the array.
要注意的另一件事是数组索引从零开始.因此,包含20个元素的数组(如int a[20]
中所示)具有有效的索引0
至19
.运行从1
到20
的循环-因此访问a[1]
到a[20]
会产生不确定的行为,因为a[20]
不存在.
The other thing to watch is that array indexing starts at zero. So an array with 20 elements (as in int a[20]
) has valid indices 0
to 19
. Running a loop from 1
to 20
- and therefore accessing a[1]
through to a[20]
gives undefined behaviour, since a[20]
does not exist.
这篇关于如何初始化“分钟"?变量正确吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!