好吧,我的程序应该创建一个数组大小 [8],然后一旦打印出来,我就使用 For 循环来查找数组中的最小数字。我遇到的问题是它似乎总是停在第二个元素并将其声明为最小。谁能告诉我我的代码有什么问题
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
void main(int argc, char* argv[])
{
const int len = 8;
int a[len];
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");
getchar();
int smallest;
for (i = 1; i < len; i++) {
if (a[i] < smallest)
smallest = a[i];
{
printf("The smallest integer is %d at position %d\n", a[i], i);
break;
getchar();
}
}
}
最佳答案
您的代码中有一些错误,如下所示:
1-初始化之前使用变量 intsmallest。 2-最后一个for循环内部的逻辑是错误的。
正确的代码是:
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");
smallest = a[0];
for ( i= 1 ; i < len ; i++ )
{
if ( a[i] < smallest )
{
smallest = a[i];
location = i+1;
}
}
printf("Smallest element is present at location %d and it's value is %d.\n", location, smallest );
getch();
}
关于c - for 循环查找数组中的最小元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22898070/