2014-09-26 37 views
1

所以我觉得我真的很接近答案。只是我无法弄清楚我到底在想什么。程序用随机数填充一个数组,然后运行它以查找哪个数字最小。一旦找到最小的数字,就会将其打印出来并与其位置一起打印出来。我有我的for循环找到最小的整数的麻烦。找到最小整数

#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(); 
    } 
} 
+0

注意:'int location = 1;'应该是'int location = 0;'else'a [0]'不能是最小的。 – chux 2014-09-26 02:45:46

回答

2

麻烦的是这样的:

location = i++; 

此行实际上改变了我的价值,这是您用于循环索引,所以某些元素会被跳过 - 基本上一半左右被跳过。

你可能想要的东西,像下面这样,这确实一个简单的任务没有改变我的价值:

location = i + 1; 
//or location = i, 
//depending on whether you want to print the location as 0-based or 1-based 
+0

此外,结果的印刷应该在循环外 – 2014-09-26 00:48:59

+0

雅我试过删除,但它似乎并没有解决这个问题。我会得到的是,第一个位置的整数总是最小的。 @Peter Pei Guo – Zanderg 2014-09-26 00:51:08

0

你有两个问题。其中一个Pete Pei Guo在他的answer中被正确识别。对于我的钱,正确的修复方法是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(); 

我不会与getchar()麻烦,但我知道使用GUI/IDE开发的人往往需要它来阻止窗口消失,不能因为程序退出。