如何找到小数点后的数字? [英] How to find digits after decimal?

查看:117
本文介绍了如何找到小数点后的数字?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想用C ++编写一个程序来输入一个十进制数字,并找出十进制
之后的数字,例如0.26547-> 5。

I want to write a program in C++ to cin a Decimal number and cout the digits after Decimal for example 0.26547 -> 5.

我写了

       int main()
 {
 int i=0,b;
float a ;
  cin>>a ;
   while(a!=0)
  {
    a*=10 ;
    b=a ;
    a-=b ;
    i+=1 ;
 }
 cout<<i ;
 }

例如对于0.258而不是3,返回20。
可以一个解释我这个代码是什么问题?
谢谢

For example for 0.258 instead of 3, returns 20. can one explain me what is the problem of this code ? thank you

推荐答案

C ++允许使用浮点数的十进制表示形式,但据我所知,所有现有实现都使用二进制表示形式。然后,将用户的十进制数字规范存储为浮点值的想法就失去了有关十进制数字的关键信息:它们不再存在。因此,要计算规范中的小数位数,必须将其存储为字符串。

C++ permits decimal representation of floating point numbers, but as far as I know all extant implementations use binary representation. And then the idea of storing the user's decimal number specification as a floating point value, loses critical information about the decimal digits: they're simply not there any more. So to count the decimal digits in the specification, you have to store it as a string.

伪代码:


  1. 输入数字指定为字符串,例如使用 getline

  2. 验证其是否为有效的数字规范,例如使用 stod

  3. 从右边扫描第一个期间,将此位置称为P。

  4. 扫描位置P处的最大十进制数字。

  1. input number specification as a string, e.g. using getline.
  2. verify that it's a valid number specification, e.g. using stod.
  3. scan for the first period from the right, call this position P.
  4. scan for the maximum number of decimal digits from position P.

这篇关于如何找到小数点后的数字?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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