PTA

7-28 求整数的位数及各位数字之和 

SRE实战 互联网时代守护先锋,助力企业售后服务体系运筹帷幄!一键直达领取阿里云限量特价优惠。

我的程序:

#include<stdio.h>
#include<math.h>

int main(){
    int n,a,b,s=0,t;
    scanf("%d",&n);
    a = (int)log10(n) + 1;
    b = a;
    while(b>1){
        b--;
        t = pow(10,b);
        s += n/t;
        n = n%t;
    }
    s += n;
    printf("%d %d",a,s);
}

网友的程序,更简洁:

#include <stdio.h>
int main(){
    int n, count, sum;
    sum = 0;
    count = 0;
    scanf("%d", &n);
    while(n!=0){
        count++;
        sum += n%10;
        n /= 10;
    }
    printf("%d %d\n", count, sum);

    return 0;
}

 

扫码关注我们
微信号:SRE实战
拒绝背锅 运筹帷幄