使用 Ascii 字符统计字符

Using Ascii characters to count characters

为什么我注释掉的代码不能统计0-9的数字? 例如当输入 happy 34567 fans# 时。数字计数器应为 5,字母计数器应为 9。

#include <stdio.h>
int main() 
{
    /*edit*/
   /* Write your code here */
   char ch;
   int letter_counter=0, num_counter=0;
   printf("Enter your characters (# to end):\n");
   while((ch = getchar()) != '#'){
       //if( ('A'<=ch<='Z') || ('a'<= ch <= 'z')){
       if ((ch >= 'A' && ch <= 'Z')  ||  (ch >= 'a' && ch <= 'z')){
           letter_counter++;
       }
       //else if('0' <=ch <= '9'){
       else if(ch >= '0' && ch <= '9') {
           num_counter++;
       }
   }
   printf("The number of digits: %d\n", num_counter);
   printf("The number of letters: %d", letter_counter);


    /*end_edit*/
   return 0;
}

你可以这样做:

#include <stdio.h>
int main() 
{
   char ch;
   int letter_counter=0, num_counter=0;

   printf("Enter your characters (# to end):\n");
   while((ch = getchar()) != '#'){
       if (ch >= 'a' && ch <= 'z')
           letter_counter += 1;
       if (ch >= 'A' && ch <= 'Z')
           letter_counter += 1;
       if (ch >= '0' && ch <= '9')
           num_counter += 1;
   }
   printf("The number of digits: %d\n", num_counter);
   printf("The number of letters: %d", letter_counter);
   return 0;
}

表达式

'0' <=ch <= '9'

'A' <= ch <= 'Z'

'a' <= ch <= 'z'

将全部计算为真,而不管 ch 的值如何。

根据rules of operator precedence,表达式

'A' <= ch <= 'Z'

相当于:

('A'<=ch) <= 'Z'

子表达式 'A'<=ch 的计算结果为真 (1) 或假 (0),因此整个表达式将等同于

0 <= 'Z'

或:

1 <= 'Z'

假设您使用的是 ASCII 兼容字符集,'Z' 将具有字符代码 90,因此整个表达式将等同于

0 <= 90

或:

1 <= 90

在这两种情况下,表达式的计算结果都为真。

这就是为什么你必须写

ch >= 'A' && ch <= 'Z'

'A' <= ch && ch <= 'Z'

而不是:

'A' <= ch <= 'Z'

此外,值得注意的是,您可以通过使用函数 isalpha and isdigit 来稍微简化您的代码。这两个功能都需要您 #include <ctype.h>.

#include <stdio.h>
#include <ctype.h>

int main() 
{
   int ch;
   int letter_counter=0, digit_counter=0;

   printf( "Enter your characters (# to end):\n" );
   while ( (ch=getchar()) != '#') {
       
       if ( isalpha( ch ) ) {
           letter_counter++;
       }
       else if ( isdigit( ch ) ) {
           digit_counter++;
       }
   }

   printf( "The number of digits: %d\n", digit_counter);
   printf( "The number of letters: %d\n", letter_counter);

   return 0;
}