How to find digits after decimal? [closed]

限于喜欢 提交于 2019-12-13 06:10:49

问题


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

I wrote this but not work correctly:

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

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


回答1:


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.

Pseudo-code:

  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.



回答2:


I am unsure why your code does not work (What compiler are you using?), but I think it might related to

b=a;

Try explicitly casting your float to an int

b = int(a);

Alternatively, you could choose not to use an int, and round a float down using the function floor by including math.h #include <math.h>

float a = 5.9f;
float b = floor(a);
a -= b;


来源:https://stackoverflow.com/questions/41197139/how-to-find-digits-after-decimal

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!