Блог пользователя dusht0814

Автор dusht0814, история, 8 лет назад, По-английски

Hello everyone,

I was working on a problem where i was given an integer p and was asked to calculate the number of digits after the decimal point in 1/p.

Ex:- Input: 100 Output: 2 as (1/100=0.01)

#include<bits/stdc++.h>
using namespace std;
int main()
{
float p;
cin>>p;
float q=1/p;
int cnt=0;
cout<<q<<"\n";
while(fmod(q,10.0)!=0)
{
q=q*10;
cnt++;
//cout<<q<<" "<<cnt<<"\n";
}
cout<<cnt-1<<"\n";
}

What i was trying to do is multiply (1/n) till it is divisible 10 and then simply print count-1 .

But the output this code is giving me is 12 in place of 2 for p=100.

Help would be appreciated :)

  • Проголосовать: нравится
  • 0
  • Проголосовать: не нравится

»
8 лет назад, # |
  Проголосовать: нравится +8 Проголосовать: не нравится

First, float data type has a very low precision so it's better to use long double instead.

Second, because of long double can't hold infinite precision checking a long double variable to be equal to 0 by using == or != will probably give false so it's better to check it like this abs(a)<1e-9

Third, the number 1/100 might be represented by 0.009999999... so after multiplying 3 times by 10 it will be 9.9999999 applying the mod 10 will remain it 9.99999 instead of making it 0 so you also need to check if fmod(q,10.0) is near to 10

finally, it's better to make fmod after multiplying by 10 in order not to make the number very huge and then losing precision

so your code will be:

#include <iostream>
#include <math.h>
using namespace std;
int main()
{
long double p;
cin>>p;
long double q=1/p;
long double y=10;
int cnt=0;
cout<<q<<"\n";
while(!(abs(fmod(q,y))<1e-9 || 10-abs(fmod(q,y))<1e-9)){
q=fmod(q*10,y);
cnt++;
//cout<<q<<" "<<cnt<<"\n";
}
cout<<cnt-1<<"\n";
}

the code will not work on some inputs like 1/3 since they will not be integer how ever times you multiply by 10, but your code will give some random answer because of limit precision