C++ - how to find the length of an integer

后端 未结 13 1417
你的背包
你的背包 2020-12-09 10:03

I\'m trying to find a way to find the length of an integer (number of digits) and then place it in an integer array. The assignment also calls for doing this without the use

13条回答
  •  悲&欢浪女
    2020-12-09 10:22

    "I mean the number of digits in an integer, i.e. "123" has a length of 3"

    int i = 123;
    
    // the "length" of 0 is 1:
    int len = 1;
    
    // and for numbers greater than 0:
    if (i > 0) {
        // we count how many times it can be divided by 10:
        // (how many times we can cut off the last digit until we end up with 0)
        for (len = 0; i > 0; len++) {
            i = i / 10;
        }
    }
    
    // and that's our "length":
    std::cout << len;
    

    outputs 3

提交回复
热议问题