c - for 循环查找数组中的最小元素

标签 c arrays forms

好吧,我的程序应该创建一个数组大小 [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/

相关文章:

c - 根据需要扩展动态内存块

c - recv()对于大量数据不起作用

c# - 如何将数组拆分为一组 n 个元素?

java - 当key的值为数组时,如何编写http get请求?

php - 将复选框项目分配给 MySQL db TEXT 列

javascript - 传递给 PayPal 表单字段的 jQuery .val 西里尔字母值

c# - 我们可以在一个表单中有多个提交类型按钮吗?

c - 如何在使用 open() 时设置文件的共享模式

c - 这个语句在 C 中是什么意思?((uint16_t)0x0001)

arrays - 如何检查空数组(结构数组)