在C中找到数组中最小数的问题
这是我编写的用于查找给定数组中最少元素的 C 程序。
但是每次输出都是“0”。我也检查过其他网站,但我发现我的程序没有问题。任何人都可以纠正这个程序中的问题。(提前致谢)
#include <stdio.h>
main()
{
int i,least,x[10];
printf("Enter the elements into the arrayn");
for (i=0;i<10;i++)
{
scanf("%d",&x[10]);
}
least=x[0];
for (i=1;i<10;i++)
{
if(least > x[i])
{
least=x[i];
}
}
printf("The least element in the array is %d", least);
}
回答
在你的代码中
scanf("%d",&x[10]);
应该
scanf("%d",&x[i]);
^^^
因为您需要逐个元素地循环遍历数组,而计数器为i.
此外,通过在 10 个元素的数组上使用索引 10,您可以逐一访问超出范围的内存并调用未定义的行为。
那说,
- 为 使用适当的签名
main(),对于托管的签名,最简单的签名是int main(void)。 - 始终检查
scanf()用户输入是否成功。scanf()不惜一切代价避免使用,使用fgets()更好。