Ç比较数字 [英] C compare numbers
问题描述
我用C编写一个程序,要求用户输入一个数字范围。恩。 1 4 6 9 5,发现其中最大的。这似乎简单,但我一直得到错误的输出。
I have to write a program in C that asks the user to enter a range of numbers. ex. 1 4 6 9 5 and finds the largest of them. This would seem simple but I consistently get wrong outputs.
我的code到目前为止,我写的是:
My code I have written so far is:
#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()
的方法,但我的最大
方法,我得到51或者,如果我把7,我得到55我的最大
方法。我很困惑。
For example, if i input the number 3, I get 3 for the putchar()
method, but as my max
method, i get 51. Or if I put in 7, i get 55 for my max
method. I am very confused.
我保持简单截至目前,所有我想做的是让第一个整数/字符输入,并将其分配给最大
。有一次我读到第二整数,把它比作最大
来看看它更大或更低。谢谢!
I am keeping simple as of now, all I want to do is to get the first integer/char input and assign it to max
. And once I read the 2nd integer, compare it to max
to see if its greater or lower. Thanks!
推荐答案
使用的getchar()你正在阅读一个字符,而不是一个数字。返回值是对应于字符的ASCII code中的整数。你可以看到 ASCII表并veridy那(char)的'7'对应于55,以及3至51。
With getchar() you are reading a char and not a number. The return value is the integer that corresponds to the ASCII code of that char. You can see the ascii table and veridy that (char) '7' corresponds to 55, and 3 to 51.
因此需要要么使用不同的函数来分析数字,或转换为ASCII code(51,55等),以它对应的实际整数。
Therefore you need either to use a different function to parse the numbers, or convert the ascii code (51, 55 etc) to the actual integer number it corresponds.
这篇关于Ç比较数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!