you get to enter a real number ( 12.345 ) you need to convert its fractional part 0.345 to the integer 345 and display it on the screen. What is the error in the loop?

 #include <iostream> #include <cmath> using namespace std; main() { double r; cin>>r; double p=1; double i_r,i_r2; double ost_r=modf(r,&i_r); cout<<modf(ost_r,&i_r2); while(modf(ost_r,&i_r2)!=0) { ost_r*=10; cout<<ost_r<<endl; } } 
  • Can you specifically describe your problem? I have no compiler did not compile. Do you have a compilation error? Or does it work incorrectly? How exactly does it work? - Zealint
  • The error here is to use the cycle in principle ... - PinkTux
  • @PinkTux how else then? - topl3niy
  • Consider the incoming number as a string, and output everything after the point. The second way: do not compare with zero (because zero almost never succeeds), but check that the resulting value is less than some small eps (modulo). - Zealint
  • @Zealint ost_r continues to increase in a cycle when it should stop - topl3niy

1 answer 1

The specificity of floating-point numbers is that you can almost never guarantee anything. For example, you enter 2.33, but in fact the number will be stored like 2.3300000000000000711 , or instead of 2.3456789 - 2.3456788999999997891 .

So the conclusion will be very unexpected for you.

Therefore, I see only such real ways ...

  1. Stake up the number of characters. Let's say three after the point. Then simply - take only the fractional part, multiply by 10^N , and output the whole part.

  2. Just enter as a string, output what is after the dot ...

  3. Write work with rational numbers like p/q and work with them :)

  • According to the 1st method. And if the input gets a number with 2 characters after the point - topl3niy
  • @ topl3niy The third will be zero :) - Harry
  • but I don’t need it: the exact fractional part is needed (1.2 or 3 numbers after a dot) - topl3niy
  • one
    It’s easiest to check the latest zeros for the presence of a three-digit number ... - Harry