【问题标题】:for loop for finding smallest element in an Array用于查找数组中最小元素的 for 循环
【发布时间】:2014-04-06 18:24:19
【问题描述】:

好的,所以我的程序假设创建一个数组大小 [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();

    }
}
}

【问题讨论】:

  • 欢迎来到 Stack Overflow。 c#c++ 标签看起来无关紧要。请阅读FAQHow to Askhelp center 作为开始..

标签: c arrays forms


【解决方案1】:

您的代码中有一些错误,如下所示:

1-变量 int minimum 在初始化之前使用。 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();
}

【讨论】:

  • 好的,所以我的主要错误是在我的 For 循环上方而不是在标题处初始化最小。以及完全放弃我对位置变量的声明。 @AnkitPandey
  • 是的,您的代码存在一些小问题,例如 - 1- 变量最小应该在使用前进行初始化。 2- for 循环内的逻辑不正确 3- Break 语句的位置不正确,逻辑不正确.. @user3504208 - 请更新您的姓名,而不是使用 user3504208 :-)
  • 是的,我对这门编程语言真的很陌生,所以我需要很长时间才能理解所有内容,但我已经开始掌握它了。我真的很感谢你的帮助。我没有意识到我的用户名就像那样奇怪。谢谢@AnkitPandey
【解决方案2】:
{
    printf("The smallest integer is %d at position %d\n", a[i], i);
    break;
    getchar();

}

此块与if 条件同时执行,这意味着一旦遇到小于smallesta[i],您就会跳出循环。

顺便说一句,您可能希望在进入循环之前将 smallest 初始化为等于 a[0]

【讨论】:

  • 我使用 break 的原因是因为它不断重复 printf 语句,我能想出阻止它的唯一方法是在它打印后中断它没有意识到它是仅运行一次后停止整个程序。谢谢@jason
【解决方案3】:
Int smallest=a[0];
for (int i=1;i<len;i++)
{
     if(a[i]<smallest)
           Smallest=a[i];
}

【讨论】:

  • 我认为我的主要问题是我休息了;在我的代码中,一旦它运行一次以比较前两个数字。我的原始作品与您在这里的作品相似。谢谢@JunaidShirwani
  • 是的,break 才是真正的问题,很高兴听到您的问题已解决。如果您认为我的回答对您有帮助,接受它会很好
  • 我很确定,但你可以试一试
猜你喜欢
  • 2019-09-18
  • 2015-04-18
  • 1970-01-01
  • 2016-10-24
  • 1970-01-01
  • 2019-01-26
  • 1970-01-01
  • 1970-01-01
  • 2020-07-31
相关资源
最近更新 更多