-2

This code calculates the number of digits of the number which we enter depending on that you always get less than 1 if you divide a number by a number that has one digit more; the program still divides until it gets less than one. I tried to define num as long integer.

#include <iostream>
#include <cmath>
using namespace std;
int main () {
int num,n,dev;
dev = 10;
n = 1;
cin >> num;
double dn = num / dev;
if (dn < 1){
        cout << n;
}
if (dn >= 1){
    while (dn >= 1){
        dev *= 10;
        dn = num / dev;
        n++;
    }
    cout << n;
}

return 0;
}

I expect that it will work on all digits.

Armali
  • 18,255
  • 14
  • 57
  • 171
  • 1
    Since both `num` and `dev` are integers, `num / dev` will be an integer division. You lose all fractions. – Some programmer dude Jan 20 '19 at 18:33
  • 1
    Welcome to SO. Have you read the [help] ? Because you are supposed to explain in the question what you already have tried to solve your problem. And you should learn how to debug, things really get easy after that. – kebs Jan 20 '19 at 18:33
  • Your question is not very well phrased, are you trying to get the number of digits a given number has? – Aykhan Hagverdili Jan 20 '19 at 18:35
  • `double dn = num / dev;` always will result in `0` you're aware of that no? – πάντα ῥεῖ Jan 20 '19 at 18:35
  • 1
    10 digits is more than max number representable by `int` on most platforms. The highest number you are likely to be able to to store is 1.8 * 10^19 with `unsigned long long`. You should probably read the imput to `std::string`, check if all chars in this string are digits and return the length of the string. – Yksisarvinen Jan 20 '19 at 18:35
  • @πάνταῥεῖ It actually works as intended, because OP is only interested in "less than one/greater than one" comparison. – Yksisarvinen Jan 20 '19 at 18:42

1 Answers1

0

Change

int num,n,dev;

to

long long num,n,dev;

Because the highest number int can have is 2,147,483,647

Radu
  • 540
  • 1
  • 7
  • 23