2017-06-17 46 views
1

我正在實現一個簡單的程序,用C查找數組中的最大和最小元素。但是在某些情況下,我得到了意想不到的輸出。請檢查this輸出。請檢查下面的代碼。根據輸入沒有得到所需的輸出

#include<stdio.h> 
#include<stdlib.h> 

int largest(int *input) 
{ 
    int i=0,large=0; 
    for(;i<input[i]!='\0';i++) 
    { 
     if(input[i]>large) 
      large=input[i]; 
    } 
    return large; 
} 

int smallest(int *input) 
{ 
    int i=0,small; 
    small=input[i]; 
    for(;i<input[i]!='\0';i++) 
    { 
     if(input[i]<small) 
      small=input[i]; 
    } 
    return small; 
} 

void main() 
{ 
    int *input; 
    int size,i=0,large,small; 
    printf("Enter size of array:\n"); 
    scanf("%d",&size); 
    printf("Enter Numbers:\n"); 
    input=(int *)malloc(size * sizeof(int)); 
    for(;i<size;i++) 
    { 
     scanf("%d",input+i); 
    } 
    large=largest(input); 
    printf("Largest element is:%d, ",large); 
    small=smallest(input); 
    printf("Smallest element is:%d\n",small); 
} 

當我將大小傳遞給函數時,程序工作正常。

int largest(int *input,int size) 
{ 
    int i=0,large=0; 
    for(;i<size;i++) 
    { 
     if(input[i]>large) 
      large=input[i]; 
    } 
    return large; 
} 

output通過執行上述功能。

我不明白這裏發生了什麼。請幫我找到解決辦法。

+1

'我的'input = calloc(size +1,sizeof(int));') – BLUEPIXY

+0

@BLUEPIXY是的,它通過使用calloc函數來完美工作。感謝您的幫助。但是我仍然不明白爲什麼它在使用malloc時不工作?你能解釋一下嗎? –

+1

您正試圖與'0'進行比較,但它並不存在於輸入數據的任何地方。 – BLUEPIXY

回答

0

不要指望由malloc()分配的內存初始化爲zero

for(;i<input[i]!='\0';i++) 

這裏i<input[i]!='\0'甚至不會,如果你的目的是要確定一個數組(其值是0)的工作進行到底。在這種情況下,您應該將最後一個元素初始化爲0,並將表達式修改爲input[i]!=0

你必須保持分配的內存大小的軌跡,它作爲一個參數傳遞,如果它被視爲一個數組

0

這裏是解決方案:

#include<stdio.h> 
    main(){ 
    int count, i, j, k; 
    float all_number[15],temp; 
    printf("\n Enter the number of input : "); 
    scanf("%d",&count); 
    for(i=0;i< count;i++){ 
     printf("\n Enter %d element : ",i); 
     scanf("%f",&all_number[i]); 
    } 
    for(j=0; j<count ; j++){ 
     for(k = j+1; k <count; k++){ 
      if(all_number[j] > all_number[k]){ 
       temp = all_number[j]; 
       all_number[j] = all_number[k]; 
       all_number[k] = temp; 
      } 
     } 
    } 

    printf("\n lowest %d element : %f",i,all_number[0]); 
    printf("\n highest%d element : %f",i,all_number[count]); 
} 
+1

歡迎來到StackOverflow並感謝您的幫助。請考慮通過解釋解決方案是什麼來改進您的答案。代碼中的註釋是這樣做的簡單方法。在這裏不太瞭解代碼的答案。順便說一句,您可能會喜歡獲得您的第一張參加[巡演]的徽章。 – Yunnosch

+1

歡迎來到Stack Overflow。請儘快閱讀[關於]和[回答]頁面。一般來說,解釋一下你在做什麼是一個好主意。目前尚不清楚可以對數據進行排序;當然沒有必要對數據進行排序以確定最大和最小。 –

+1

@Yunnosch:我想偉大的思想都一樣...... –