简体   繁体   中英

c++ Program Not working

I am a newbie in c++ I am trying to make a program which counts no of digits in an input Here is my code

#include "stdafx.h"
#include <iostream>

int i, n, r, t,  large;
float f;
int main() {
    do {
        using namespace  std;
        cout<<"Enter a Number"<<endl;
        cin>>n;

        do {
            f=n/10;
            i=0;
            t=i + 1;
        } while (f > 1);

        cout<<"No of Digits = ";
        cout<<t<<endl;

        cout<<"Do u wish to continue"<<endl;
        cin>>r;
    }
    while (r!='y');
}

This works Well if i add a single digit No This is the output when i add single digit No

输出一位数字否

But when i add more than 1 digit no it stucks and doesn't moves ahead here is the output when i add more that 1 no

输出超过1位数字否

Can someone please help me

You have an infinite loop

do {
    f=n/10;
    i=0;
    t=i + 1;
} while (f > 1);

If n is 2 digits, then you keep reassigning the same values. I think you intended to change the first line

f = n; // new line
t = 0; // moved line
do {
    f = f / 10; // changed line
    t = t + 1;  // changed line
} while (f >= 1);

In the program variable f should be an int.

The loop should be as follows,

f=n;
i=0;

do {
    f=f/10;
    i++;
}while(f > 0);

cout<<"\nNumber of Digits : "<<i;

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM