2014-09-26 60 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開發的人往往需要它來阻止窗口消失,不能因爲程序退出。