.通过编程实现,统计1~n有多少个9 (n通过参数传入)



#include<stdio.h>

int count9(int n)
{
        int i,r,temp;
        int j=0;
        for(i=1;i<=n;i++)
        {
                temp=i;
                while(temp!=0)
                {
                        r=temp%10;
                        temp=temp/10;
                        if(r==9)
                        {
                                j++;
                        }
                }
        }
        return j;
}
int main()
{
        int n,m;
        printf("input a number:\n");
        scanf("%d",&n);
        m=count9(n);
        printf("The number of 9 is:%d\n",m);
        return 0;
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
下面是一个使用指针实现统计字符串中大写字母、小写字母、数字和其他字符个数的 C 语言代码示例: ```c #include <stdio.h> void count_chars(char *str, int *upper, int *lower, int *digit, int *other) { while (*str != '\0') { if (*str >= 'A' && *str <= 'Z') { (*upper)++; } else if (*str >= 'a' && *str <= 'z') { (*lower)++; } else if (*str >= '0' && *str <= '9') { (*digit)++; } else { (*other)++; } str++; } } int main() { char str[100]; int upper = 0, lower = 0, digit = 0, other = 0; printf("请输入字符串:"); fgets(str, 100, stdin); count_chars(str, &upper, &lower, &digit, &other); printf("大写字母个数:%d\n", upper); printf("小写字母个数:%d\n", lower); printf("数字个数:%d\n", digit); printf("其他字符个数:%d\n", other); return 0; } ``` 在 `count_chars` 函数中,我们使用了指针来修改传入参数。`str` 是指向字符串的指针,而 `upper`、`lower`、`digit` 和 `other` 都是指向整型变量的指针。在函数中,我们使用指针来统计字符串中的各种字符个数,并将结果保存在对应的整型变量中。 在 `main` 函数中,我们使用 `fgets` 函数获取用户输入的字符串,并将字符串传递给 `count_chars` 函数进行统计。最后,我们输出各种字符的个数。 注意:在使用 `fgets` 函数获取用户输入的字符串时,需要注意字符串末尾会自动添加一个换行符,因此需要在字符串中去掉换行符。这里我们可以使用下面的代码去掉换行符: ```c str[strlen(str) - 1] = '\0'; ```

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值