2015-10-03 90 views
-4

我用C編寫一個程序,要求用戶輸入一個數字範圍。恩。 1 4 6 9 5並找到它們中最大的一個。這看起來很簡單,但我一直得到錯誤的結果。ç比較數字

到目前爲止我的代碼我寫的是:

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


main() 
{ 
    char max; 
    int count = 0; 
    char numbers; 
    printf("Enter a sequence of numbers\n"); 
    max = getchar(); 
    while((numbers = getchar()) != EOF) 
    { 


     printf("Max: %d", max); 
     putchar(numbers); 
    } 

例如,如果我輸入數字3,我得到3爲putchar()方法,但我max方法,我得到51或者,如果我把7,我得到55我的max方法。我很困擾。

我現在保持簡單,所有我想要做的就是獲取第一個整數/字符輸入並將其分配給max。一旦我讀到第二個整數,將其與max進行比較,以查看其大小。謝謝!

+2

你讀過[手冊頁](http://linux.die.net/man/3/getchar)? –

+0

也[這](http://www.asciitable.com/)可能會有所幫助。 –

+1

特別是,首先比較手冊頁。例如scanf和getchar。哦,也是printf的一個。 (字符的格式是%c,而不是%d)。 –

回答

1

在使用getchar()你正在閱讀一個字符,而不是一個數字。返回值是與該char的ASCII代碼對應的整數。你可以看到ascii table和veridy(char)'7'對應於55,3和51.

因此,您需要使用不同的函數來解析數字,或者轉換ascii代碼(51,55等)到它對應的實際整數。

0

的getchar()函數是不會幫你因爲它的讀取字符。 你需要的是類似的scanf():

#include <stdio.h> 

#define N 4 

int GetMax(int *arr); 

int main() 
{ 
    int arr[N]; 

    for(int x = 0 ; x < N ; x++) 
    { 
     printf("Enter number %d : ", x + 1); 
     scanf("%d",&arr[x]); 
    } 

    printf("max value : %d\n",GetMax(arr)); 

} 

int GetMax(int *arr) 
{ 
    int max = arr[0]; 

    for(int x = 1 ; x < N ; x++) 
    { 
     if(arr[x] > max) 
      max = arr[x]; 
    } 

    return max; 
}