当前位置:编程学习 > C/C++ >>

c语言数组问题

题:输入一行数字字符,请用数组元素作为计数器来统计每个数字字符的个数。用下标为0的元素统计字符“0”的个数,下标为1的元素统计字符为“1”的个数,。。。。

答案:

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

 

/*********************************************************************************************
   ---
  @Description: 统计一个字符串中所出现在每个([0 9])数字字符的个数,
                         写入到ditcnt指向的作为计数表功能的数组中。
  @Input : 包含数字字符的串
  @Output: 计数表
  @Return: 无
********************************************************************************************/
void count_num(size_t ditcnt[10], const char *str)
{
        //memset(ditcnt, 0, 10);
        for(; *str; ++str) {
                if(isdigit(*str))  // (*str >= '0' && *str <= '9')
                        ditcnt[*str - '0']++;
        }
}


int main(void)
{
        char str[BUFSIZ];

        size_t cnt[10] = {0};
        size_t i;

 

        fgets(str, BUFSIZ, stdin);
        count_num(cnt, str);
        puts("计数结果:\n数字  -  个数");
        puts("-----------------------");
        for(i = 0; i < 10; ++i) {
                if(cnt[i] != 0)
                        printf("%-5d -%5d\n", i, cnt[i]);
        }

        getchar();

 

        return 0;

}


 

#include<stdio.h>

main()

{

 int a[10];char b[99];

int i;
scanf("%s",b);

for(i=0;i<10;i++)
a[i]=0;
for(i=0;i<strlen(b);i++)
switch(b[i]) {
  case '0': a[0]++ ; break;
  case '1': a[1]++ ; break;
  case '2': a[2]++ ; break;
  case '3': a[3]++ ; break;
  case '4': a[4]++ ; break;
  case '5': a[5]++ ; break;
  case '6': a[6]++ ; break;
  case '7': a[7]++ ; break;
  case '8': a[8]++ ; break;
  case '9': a[9]++ ; break;
  default:       break;


}

for(i=0;i<10;i++)
  printf("%d---------------%d\n",i,a[i]);

 

}

 

上一个:什么是c语言
下一个:C 语言的问题

CopyRight © 2012 站长网 编程知识问答 www.zzzyk.com All Rights Reserved
部份技术文章来自网络,