Caca Caca - 3 years ago 118
C++ Question

I feel like my code is right, but the execution is still wrong, why?

I'm trying to make a digit counter with loop. I am quite sure that my code is right, but the execution is different than what I wanted to. Can someone tell me where I did it wrong?

Here is my code

#include <iostream>
using namespace std;

int main()
{
long long x,y;
int i;

cout << "Input X : ";
cin >> x;

i=0;
y=x;

while(x>0){
x=x/10;
i++;
cout <<i;
}

cout <<y<<" is made up of "<<i<<" digits."<<endl;

return 0;
}


So, the execution is :

Input X : 5000

12345000 is made up of 4 digits

Why the ouput is not the same as the input? What is wrong?

Answer Source

The 1234 in front of 12345000 is due to you having the cout <<i statement at the end of your while loop.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download