C 求最小整数
所以我觉得我真的很接近答案。只是我不知道我到底错过了什么。程序用随机数填充一个数组,然后运行它以找出哪个数最小。一旦找到最小的数字,它就会将其连同位置一起打印出来。我的for循环在寻找最小整数时遇到了麻烦C 求最小整数,c,arrays,for-loop,C,Arrays,For Loop,所以我觉得我真的很接近答案。只是我不知道我到底错过了什么。程序用随机数填充一个数组,然后运行它以找出哪个数最小。一旦找到最小的数字,它就会将其连同位置一起打印出来。我的for循环在寻找最小整数时遇到了麻烦 #include <stdio.h> #include <stdlib.h> #include <time.h> void main(int argc, char* argv[]) { const int len = 8; int a[le
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(int argc, char* argv[])
{
const int len = 8;
int a[len];
int smallest;
int location =1;
int i;
srand(time(0));
//Fill the array
for(i = 0; i < len; ++i)
{
a[i] = rand() % 100;
}
//Print the array
for (i = 0; i < len; ++i)
{
printf("%d ", a[i]);
}
printf("\n");
//Find the smallest integer
smallest = a[0];
for (i = 1; i < len; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
location = i++;
}
printf("The smallest integer is %d at position %d\n", smallest, location);
getchar();
}
}
#包括
#包括
#包括
void main(int argc,char*argv[])
{
常数int len=8;
int a[len];
int最小;
int位置=1;
int i;
srand(时间(0));
//填充数组
对于(i=0;i
问题在于:
location = i++;
这一行实际上改变了i的值,i是用于循环的索引,因此跳过了一些元素,基本上跳过了一半
您可能想要以下类似的东西,它在不更改i的值的情况下执行简单赋值:
location = i + 1;
//or location = i,
//depending on whether you want to print the location as 0-based or 1-based
你有两个问题。一个是正确识别的在他的。就我的钱而言,正确的修复方法是
location=i代码>但这取决于您要报告的内容
另一个问题是printf()
调用在循环中。你应该:
smallest = a[0];
for (i = 1; i < len; i++)
{
if (a[i] < smallest)
{
smallest = a[i];
location = i;
}
}
printf("The smallest integer is %d at position %d\n", smallest, location);
getchar();
最小值=a[0];
对于(i=1;i
我不想麻烦使用getchar()
,但我知道使用GUI/IDE开发的人往往需要它来防止窗口消失,因为程序退出了。此外,结果的打印应该在循环之外。我尝试过删除它,但它似乎无法解决问题。我得到的只是第一个位置的整数总是最小的@Peter Pei Guotnote:int location=1代码>应该是int location=0
elsea[0]
永远不能是最小的。