使用while循环计数数字 [英] Counting digits using while loop

查看:668
本文介绍了使用while循环计数数字的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我最近制作了一个程序,需要检查用户输入的数字中的数字位数。因此,我做了以下代码:

  int x; 
cout<< 输入数字:;
cin>> X;
x / = 10;
while(x> 0)
{
count ++;
x = x / 10;
}

从我可以告诉(即使有限的经验)



有没有人知道如何改进这个代码(而不是使用内置的c ++函数)?



在这个例子中,你可以读取一个字符串,



这里是对数的例子:

  #include< iostream> 
#include< cmath>

using namespace std;

int main()
{
double n;
cout<< 输入数字:;
cin>> n;

cout<< 日志10是< log10(n)<< endl;
cout<< 数字是< ceil(log 10(fabs(n)+1))< endl;
return 0;
}


I was recently making a program which needed to check the number of digits in a number inputted by the user. As a result I made the following code:

int x;    
cout << "Enter a number: ";
cin >> x;
x /= 10;
while(x > 0)
{
  count++;
  x = x/10;
}

From what I can tell (even with my limited experience) is that it seems crude and rather unelegant.

Does anyone have an idea on how to improve this code (while not using an inbuilt c++ function)?

解决方案

In your particular example you could read the number as a string and count the number of characters.

But for the general case, you can do it your way or you can use a base-10 logarithm.

Here is the logarithm example:

#include <iostream>
#include <cmath>

using namespace std;

int main()
{
    double n;
    cout << "Enter a number: ";
    cin >> n;

    cout << "Log 10 is " << log10(n) << endl;
    cout << "Digits are " << ceil(log10(fabs(n)+1)) << endl;
    return 0;
}

这篇关于使用while循环计数数字的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆