2015-10-03 37 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; 
}