C++ 计算输入数字的位数两种方法总结

04. September 2016 笔记 0
方法一
#include <iostream>

int main(int argc, const char * argv[]) {

    int sum;

    int j;

    while (scanf("%d",&sum)) {

        j=1;

        do {

            sum=sum/10;

            if(sum>0){

                j++;

            }

        } while (sum!=0);

     std::cout<<j<< std::endl;

        }

     return 0;

}
方法二

#include <iostream>

#include "string"

int main(int argc, const char * argv[]) {

    int sum;

    char str[10];

    std::string lijian;

    while (scanf("%d",&sum)) {

        sprintf(str, "%d",sum);

        std::string lijians=str;

        std::cout<<lijians.length();

    };

     return 0;

}

Leave a Reply

Your email address will not be published. Required fields are marked *