[刷题] PTA 7-28 求整数的位数及各位数字之和

我的程序:

#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;
}

 

posted @ 2019-04-17 13:40  cxc1357  阅读(618)  评论(0编辑  收藏  举报